2012-08-07 31 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]; 

从那里你可以做任何你想要的字符串。