1. 了解NSUserDefaults以及它可以直接存储的类型
NSUserDefaults是一个单例,在整个程序中只有一个实例对象,他可以用于数据的永久保存,而且简单实用,这是它可以让数据自由传递的一个前提,也是大家喜欢用它保存简单数据的一个主要原因。
NSUserDefaults支持的类型
- NSNumber
- NSString
- NSDate
- NSArray
- NSDictionary
- BOOL
2. 简单实用
写
NSString *hello = @"Hello world";
NSUserDefault *default = [NSUserDefault standardUserDefaults];
[default setObject:hello forKey:@"user_hello"];
取
NSString *hello = [default objectForKey:@"user_hello"];
3. 自定义数据存储
@interface Student : NSObject <NSCoding> //实现协议NSCoding
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *studentId;
@property (nonatomic, copy) NSString *sex;
@end
.m中实现协议方法
@implementation Student
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:self.studentId forKey:@"studentId"];
[aCoder encodeObject:self.sex forKey:@"sex"];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.studentId = [aDecoder decodeObjectForKey:@"studentId"];
self.sex = [aDecoder decodeObjectForKey:@"sex"];
}
return self;
}
@end
将自定义的数据转化为NSData数据
Student *student = [[Student alloc] init];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];
//转化为NSData之后就可以存到NSUserDefault中了
数据解码
Student *student = [NSKeyedUnarchiver unarchiveObjectWithData:data];