可能的重复项:
如何写到plist成功?
我想简单地在 Plist 文件中编写 UISwitch 的布尔状态(真或假)。
这是我已经得到的,但 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
我只想通过切换 uiswitch 来更改 plist 文件中的值(真或假)。
我应该使用 NSUserDefaults 吗? :)
我读了它,但我从来没有得到,如何在 NSUserDefaults 中设置 plist 路径
谢谢
我会说你应该创建一个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];
从那里你可以用这个字符串做任何你想做的事情。