界面图:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)save:(id)sender {
// 单例对象
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
[def setObject:@"xmg" forKey:@"name"];
[def setInteger:10 forKey:@"age"];
//立即写入,现在iOS9之后,这句话可以不写
[def synchronize];
}
- (IBAction)read:(id)sender {
//从偏好设置里面获取数据
// 单例对象
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString *name = [def objectForKey:@"name"];
NSInteger age = [def integerForKey:@"age"];
NSLog(@"name = %@,age = %ld",name,age);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",NSHomeDirectory());
}
@end
程序运行前:Preferences目录图片:
程序运行后,点击保存按钮Preferences目录效果图片:
程序运行后,点击读取按钮效果图片:
- 注意,plist方式存储和偏好设置方式存储不能存放自定义对象要想,存放自定义对象,可以通过归档方式存储