归档自定义对象

2016-06-03  本文已影响21人  张小泺

对于归档的对象,其类要服从NSCoding协议

- (void)encodeWithCoder:(NSCoder *)aCoder {

   unsigned propertyCount = 0;

   objc_property_t *ps = class_copyPropertyList([RepairDetailInfo class], &propertyCount);

   for (int i = 0; i < propertyCount; i ++) {

       objc_property_t p = ps[i];

       const char *propertyName = property_getName(p);

       NSString *key = [NSString stringWithUTF8String:propertyName];

       id value = [self valueForKey:key];

       [aCoder encodeObject:value forKey:key];

   }

   free(ps);

}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {

   if (self = [super init]) {

       unsigned propertyCount = 0;

       objc_property_t *ps = class_copyPropertyList([RepairDetailInfo class], &propertyCount);

       for (int i = 0; i < propertyCount; i ++) {

           objc_property_t property = ps[i];

           const char *propertyName = property_getName(property);

           NSString *key = [NSString stringWithUTF8String:propertyName];

           id value = [aDecoder decodeObjectForKey:key];

           [self setValue:value forKey:key];

       }

       free(ps);

   }

   return self;

}
上一篇 下一篇

猜你喜欢

热点阅读