// 字典---- 自定义对象不能用于writeToFile保存,需要用于归档来进行保存。
NSArray *dicArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *dicPath = [dicArray lastObject];
dicPath = [dicPath stringByAppendingPathComponent:@"dic.plist"];
NSLog(@"%@--------",dicPath);
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
User *user = nil;
for (int i = 0; i<10; i++) {
NSString *userName = [NSString stringWithFormat:@"麦子--%d",i];
NSString *password = [NSString stringWithFormat:@"密码--%d",i];
NSString *sex = [NSString stringWithFormat:@"男"];
user = [[User alloc] initWithUserName:userName password:password sex:sex];
[dic setObject:user forKey:[NSNumber numberWithInt:i]];
}
bool flag = [NSKeyedArchiver archiveRootObject:dic toFile:dicPath];
if (flag) {
NSLog(@"字典保存成功");
}else{
NSLog(@"保存失败");
}
NSMutableDictionary *dicData = [NSKeyedUnarchiver unarchiveObjectWithFile:dicPath];
NSLog(@"%@---",dicData);
[dic removeObjectForKey:[NSNumber numberWithInt:1]];
[dic removeObjectForKey:[NSNumber numberWithInt:2]];
[dic removeObjectForKey:[NSNumber numberWithInt:3]];
[NSKeyedArchiver archiveRootObject:dic toFile:dicPath]; //删除后重新写入
NSMutableDictionary *dicDataB = [NSKeyedUnarchiver unarchiveObjectWithFile:dicPath];
NSLog(@"%@---",dicDataB);
在这之前, 自定义对象需要实现NSCopy协议,实现下面两个方法。
@implementation User
- (instancetype)initWithUserName:(NSString *)userName password:(NSString *)password sex:(NSString *)sex{
self = [super init];
if (self) {
self.userName = userName;
self.password = password;
self.sex = sex;
}
return self;
}
/***加密*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.userName forKey:@"userName"];
[aCoder encodeObject:self.password forKey:@"password"];
[aCoder encodeObject:self.sex forKey:@"sex"];
}
/**解密*/
- (id)initWithCoder:(NSCoder *)aDecoder{
self = [super init];
if (self != nil) {
self.userName = [aDecoder decodeObjectForKey:@"userName"];
self.password = [aDecoder decodeObjectForKey:@"password"];
self.sex = [aDecoder decodeObjectForKey:@"sex"];
}
return self;
}