整理--iOS如何把一个包含自定义对象的数组序列化到磁盘

想把一个包含自定义的对象的数组写到磁盘
如下:
User *user1 = [User alloc] init];
User *user2 = [User alloc] init];
NSArray *userArr = @[user1,user2];

方法如下:

先将自定义对象实现NSCoding协议,然后在.m里面实现下面两个方法。

-(instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (self) {
        self.objectID = [aDecoder decodeObjectForKey:@"objectID"];
        self.createdAt = [aDecoder decodeObjectForKey:@"createdAt"];
        self.updatedAt = [aDecoder decodeObjectForKey:@"updatedAt"];
    }
    return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.objectID forKey:@"objectID"];
    [aCoder encodeObject:self.createdAt forKey:@"createdAt"];
    [aCoder encodeObject:self.updatedAt forKey:@"updatedAt"];
}

再然后用NSKeyedArchiver就可以了。

NSData* tempArchive = [NSKeyedArchiver archivedDataWithRootObject:userArr];
NSArray* arr = [NSKeyedUnarchiver unarchiveObjectWithData:tempArchive];


你可能感兴趣的:(NSArray,Object-C)