1.NSUserDefault 里面存数据
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
//需要将你需要存储的数据转成data
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourObject];
[currentDefaults setObject:data forKey:@"yourKeyName"];
2.接下来就是在 NSUserDefault 里面取数据
NSData *data = [currentDefaults objectForKey:@"yourKeyName"];
yourObjectType * obj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
3.如果数组中的数据是实体类,则需要遵守NSCoding协议
@interface MyModel:NSObject<NSCoding>
@property (copy,nonatomic)NSString * name;
@property (nonatomic)int age;
@end
@implementation MyModel
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"kName"];
self.age = [aDecoder decodeInt32ForKey:@"kAge"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.name forKey:@"kName"];
[aCoder encodeInt32:self.age forKey:@"kAge"];
}
网友评论