自定义对象写入到plist文件

// 字典---- 自定义对象不能用于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;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值