NSUserDefaults
适用于快速读取小规模的数据
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];复制代码
写入数据
NSString *string = @"hahaha";[standardDefaults setObject:string forKey:@"myKey"];[standardDefaults synchronize];// 写完别忘了同步复制代码
读取数据
NSString *value = [standardDefaults objectForKey:@"myKey"];复制代码
NSUserDefaults
可以理解成键值对
有时在写数据之前,想判断下这个健是否已经设置过默认值
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];if ([standardDefaults stringForKey:@"favoriteColor"] == nil) { [standardDefaults setObject:@"Green" forKey:@"favoriteColor"]; [standardDefaults synchronize];}复制代码
其实可以使用 registerDefaults:
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];[standardDefaults registerDefaults:@{@"favoriteColor": @"Green"}];[standardDefaults synchronize];复制代码
每次程序启动的时候调用 registerDefaults:
方法都是安全的,完全可以将这个方法的调用放到 applicationDidFinishLaunching:
方法中,这个方法永远都不会覆盖用户设置的值。
但是并不是所有类型的对象都能够直接放入 NSUserDefaults
,NSUserDefaults
只支持 Foundation
类型的对象,如果自定义 NSObject
对象存入 NSUserDefaults
就要实现 NSCoding
协议了,比如:
@interface Person : NSObject@property (nonatomic, copy) NSString *age;@property (nonatomic, copy) NSString *name;- (id)initWithCoder:(NSCoder *)coder;- (void)encodeWithCoder:(NSCoder *)coder;@implementation Person- (id)initWithCoder:(NSCoder *)coder { if (self = [super init]) { self.age = [coder decodeObjectForKey:@"age"]; self.name = [coder decodeObjectForKey:@"name"]; } return self;}- (void)encodeWithCoder: (NSCoder *)coder { [coder encodeObject:self.age forKey:@"age"]; [coder encodeObject:self.name forKey:@"name"];}复制代码
然后再存取时通过 NSData
做载体:
存入
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];Person *person = [[Person alloc] init];NSData *personData = [NSKeyedArchiver archivedDataWithRootObject:person];[standardDefaults setObject:personData forKey:@"personKey"];[standardDefaults synchronize];复制代码
读取
NSData *newPersonData = [standardDefaults objectForKey:"personKey"];Person *Person = [NSKeyedUnarchiver unarchiveObjectWithData:newPersonData];复制代码