您可以使用目标- c 运行时间查找对象的所有属性并解码它们, 但我不推荐它。 如果您没有解码, 我可以为您创建一个简单的示例 。
举个例子:
#import <objc/runtime.h>
void decodePropertiesOfObjectFromCoder(id obj, NSCoder *coder)
{
// copy the property list
unsigned propertyCount;
objc_property_t *properties = class_copyPropertyList([obj class], &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = properties[i];
char *readonly = property_copyAttributeValue(property, "R");
if (readonly)
{
free(readonly);
continue;
}
NSString *propName = [NSString stringWithUTF8String:property_getName(property)];
@try
{
[obj setValue:[coder decodeObjectForKey:propName] forKey:propName];
}
@catch (NSException *exception) {
if (![exception.name isEqualToString:@"NSUnknownKeyException"])
{
@throw exception;
}
NSLog(@"Couldn t decode value for key %@.", propName);
}
}
free(properties);
}
void encodePropertiesOfObjectToCoder(id obj, NSCoder *coder)
{
// copy the property list
unsigned propertyCount;
objc_property_t *properties = class_copyPropertyList([obj class], &propertyCount);
for (int i = 0; i < propertyCount; i++) {
objc_property_t property = properties[i];
char *readonly = property_copyAttributeValue(property, "R");
if (readonly)
{
free(readonly);
continue;
}
NSString *propName = [NSString stringWithUTF8String:property_getName(property)];
@try {
[coder encodeObject:[obj valueForKey:propName] forKey:propName];
}
@catch (NSException *exception) {
if (![exception.name isEqualToString:@"NSUnknownKeyException"])
{
@throw exception;
}
NSLog(@"Couldn t encode value for key %@.", propName);
}
}
free(properties);
}
__attribute__((constructor))
static void setDefaultNSCodingHandler()
{
class_addMethod([NSObject class], @selector(encodeWithCoder:), imp_implementationWithBlock((__bridge void *)[^(id self, NSCoder *coder) {
encodePropertiesOfObjectToCoder(self, coder);
} copy]), "v@:@");
class_addMethod([NSObject class], @selector(initWithCoder:), imp_implementationWithBlock((__bridge void *)[^(id self, NSCoder *coder) {
if ((self = [NSObject instanceMethodForSelector:@selector(init)](self, @selector(init))))
{
decodePropertiesOfObjectFromCoder(self, coder);
}
return self;
} copy]), "v@:@");
}
这将允许您编码任何显示足够属性以进行自我重建的物体。