你的位置:首页 > 操作系统

[操作系统]NSUserDefaults 、对象归档


 NSUserDefaults

@interface Person : NSObject <NSCoding>
@property (nonatomic, assign) NSInteger ID;
@property (nonatomic, copy) NSString *name;
@end

 

// 存

 NSUserDefaults *user = [NSUserDefaults standardUserDefaults];

[user  setInteger:ID forKey:@”ID”];
[user setObject:name forKey:@”name”];

[user synchronize];

// 取

NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”ID”];
NSString* name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”];

 

按对象存取

// 存
[user setObject:self forKey:@”user”];

[user synchronize];

// 取
User* u = [user objectForKey”@”user”];

 

2.对象归档
要使用对象归档,对象必须实现NSCoding协议.大部分Object C对象都符合NSCoding协议,也可以在自定义对象中实现NSCoding协议,要实现NSCoding协议,实现两个方法:
- (void) encodeWithCoder:(NSCoder *)encoder ;

-(void)initWithCoder:(NSCoder *)encoder.
同时,建议对象也同时实现NSCopying协议,该协议允许复制对象,要实现NSCopying协议须实现 -(id)copyWithZone:(NSZone *)zone 方法 。
@interface Person : NSObject <NSCoding>
@property (nonatomic, assign) NSInteger ID;
@property (nonatomic, copy) NSString *name;
@end

@implementation User
// 以下两个方法一定要实现,不然在调用的时候会crash
- (void)encodeWithCoder:(NSCoder *)aCoder; 
{
// 这里放置需要持久化的属性
[aCoder encodeObject:[NSNumber numberWithInteger:self.ID] forKey:@”ID”];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [self init])
{
//  这里务必和encodeWithCoder方法里面的内容一致,不然会读不到数据
self.userID = [[aDecoder decodeObjectForKey:@"ID"] integerValue];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}

// 使用方法
+ (BOOL)save {
NSError *error = nil;
// 确定存储路径,一般是Document目录下的文件
NSString* fileName = [self getFileName];
NSString* filePath = [self getFilePath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(@”创建用户文件目录失败”);
return NO;
}
return [NSKeyedArchiver archiveRootObject:self toFile:[fileName:userId]];
}

@end