今晚写这篇文章就是为了这个目的;不要忘记#import!这假设你的类中的所有@properties 都是 NSObject 形式,所以 NSNumber 而不是 float 等。
#import <objc/runtime.h>
-(id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
uint count;
objc_property_t *properties = class_copyPropertyList(self.class, &count);
for (int i = 0; i < count ; i++) {
const char* propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
NSValue *value = [decoder decodeObjectForKey:key];
[self setValue:value forKey:key];
}
free(properties);
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
uint count;
objc_property_t *properties = class_copyPropertyList(self.class, &count);
for (int i = 0; i < count ; i++) {
const char* propertyName = property_getName(properties[i]);
NSString *key = [NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding];
NSValue *value = [self valueForKey:key];
[encoder encodeObject:value forKey:key];
}
free(properties);
}