object-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@:@");
}
これにより、それ自体を再構築するのに十分なプロパティを公開するオブジェクトをエンコードできます。