首页 > 系统 > iOS > 正文

iOS 对象的归档、解档 runtime

2019-11-09 17:30:27
字体:
来源:转载
供稿:网友

iOS 对象的归档、解档 runtime

若要实例对象实现归档解档,需要该类遵守NSCoding协议,及以下协议方法

项目中以YCArchiveBase类为例,可直接添加属性使用

PRagma mark - NSCoding

(void)encodeWithCoder:(NSCoder *)aCoder{ unsigned int count = 0; //取出所有属性 objc_property_t *properties = class_copyPropertyList([self class], &count); //遍历属性 for (int i = 0; i < count; i++) { //获取当前遍历的属性的名称 const char *propertyName = property_getName(properties[i]); NSString *name = [NSString stringWithUTF8String:propertyName];

id value = [self valueForKey:name];[aCoder encodeObject:value forKey:name];

} }

(instancetype)initWithCoder:(NSCoder *)aDecoder{

unsigned int count =0; //1.取出所有的属性 objc_property_t *propertes = class_copyPropertyList([self class], &count); //2.遍历所有的属性 for (int i = 0; i < count; i++) { //获取当前遍历到的属性名称 const char *propertyName = property_getName(propertes[i]); NSString *name = [NSString stringWithUTF8String:propertyName]; //解归档前遍历得到的属性的值 id value = [aDecoder decodeObjectForKey:name]; // self.className = [decoder decodeObjectForKey:@”className”]; [self setValue:value forKey:name]; } return self; }

归档和接档的操作以类方法实现如下(可自己创建管理类分离出去): ArchiveFilePath 为文件存储路径 + (void)archiveWithObjc:(id)objc{

NSMutableData *data = [NSMutableData data];//归档NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];[archiver encodeObject:objc forKey:@"archive"];[archiver finishEncoding];NSLog(@"data:%@",data);[data writeToFile:ArchiveFilePath atomically:YES];

}

(id)unarchive{ //解档 NSData *unData = [NSData dataWithContentsOfFile:ArchiveFilePath]; NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:unData]; YCArchiveBase *unmodel = [unarchiver decodeObjectForKey:@”archive”]; return unmodel; }

使用: YCArchiveBase *model = [[YCArchiveBase alloc]init]; model.name = @”testname”; model.num = 23; model.address = @”address”; model.ddd = 23.0;

//归档[YCArchiveBase archiveWithObjc:model];//解档YCArchiveBase *unmodel = [YCArchiveBase unarchive];NSLog(@"archiver:%@",unmodel.name);

git: https://github.com/yuchenArron/Archiver-Demo 到此结束


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表