自定义对象的本地化存储

1、首先该对象需要遵守NSCoding协议 2、直接上代码

//归档
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.type forKey:@"type"];
    [aCoder encodeObject:self.id forKey:@"id"];
    [aCoder encodeObject:self.createDate forKey:@"createDate"];
    [aCoder encodeObject:self.content forKey:@"content"];
    [aCoder encodeObject:self.modifyDate forKey:@"modifyDate"];
    [aCoder encodeObject:self.sendType forKey:@"sendType"];
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:@(self.isNewMessage) forKey:@"isNewMessage"];
}
//解档
-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        self.type = [aDecoder decodeObjectForKey:@"type"];
        self.id = [aDecoder decodeObjectForKey:@"id"];
        self.createDate = [aDecoder decodeObjectForKey:@"createDate"];
        self.content = [aDecoder decodeObjectForKey:@"content"];
        self.modifyDate = [aDecoder decodeObjectForKey:@"modifyDate"];
        self.sendType = [aDecoder decodeObjectForKey:@"sendType"];
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.isNewMessage = [[aDecoder decodeObjectForKey:@"isNewMessage"] boolValue];
    }
    return self;
}

3、保存

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"messages.data"];
    BOOL isTrueWrite = [NSKeyedArchiver archiveRootObject:messagesData toFile:filePath];

4、读取

NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
                for (MessageModel *model in arr) {
                    NSLog(@"%@",model.title);
                }

转载于:https://my.oschina.net/u/2461772/blog/680648

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值