2012-08-07 46 views
-1

可能重複:
How to write to plist successfully?目的寫C UISwitch在plist中狀態的關鍵

我想簡單地寫一個UISwitch的布爾狀態中(true或false) Plist文件。

以下是我已經有了,但價值不plist中改變:

.H

#import <UIKit/UIKit.h> 

@interface ViewController : UIViewController { 


    IBOutlet UISwitch *mySwitch; 

} 

-(IBAction)changeThingsInPlist:(id)sender; 

@end 

.M

#import "ViewController.h" 

BOOL changeThing; 
#define PLIST_PATH @"/var/mobile/Library/Preferences/com.myname.plistname.plist" 

@interface ViewController() 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 


    changeThing = [[[NSDictionary dictionaryWithContentsOfFile:PLIST_PATH]valueForKey:@"changeThing"]boolValue]; 

} 

-(IBAction)changeThingsInPlist:(id)sender { 

    if (mySwitch.on = YES) { 
     changeThing = true; 
    } 
    else { 
     changeThing = false; 
    } 
} 

- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 

@end 

我只是想改變數值(true或false)通過切換uiswitch在plist文件中。

我應該使用NSUserDefaults嗎? :)

我讀到它,但我從來沒有,如何設置的plist路徑在NSUserDefaults的

謝謝

+2

爲什麼不使用'NSUserDefaults'來取代這個單獨的值呢? – holex 2012-08-07 13:28:55

+0

只需按照此問題上接受的答案, http://stackoverflow.com/questions/7254596/how-to-write-to-plist-successfully – doNotCheckMyBlog 2012-08-07 13:30:08

回答

0

我要說的是,你應該創建一個NSString,並設置它的價值基於UISwitch的布爾值。

NSString *valueOfSwitch; 
if (mySwitch.on == YES){ 
valueOfSwitch = [NSString stringWithFormat:@"ON"]; 
} 
else { 
valueOfSwitch = [NSString stringWithFormat:@"OFF"]; 
} 

然後,你應該把這個字符串放在NSUserDefaults中,像這樣。

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
[defaults setObject:valueOfSwitch forKey:@"switchValue"]; //remember this for retrieving 
[defaults synchronize]; 

然後要檢索此字符串,請執行此操作。

NSUserDefaults *data = [NSUserDefaults standardUserDefaults]; 
NSString *switchString = [data objectForKey:@"switchValue"]; //same key that you used for saving 
[data synchronize]; 

從那裏你可以做任何你想要的字符串。