名前が一致する場合にプロパティを XML ノードに再帰的にマップするメソッドを定義することになりました。これが機能するには、プロパティの命名規則とデータ型が重要です。
ここに投稿する前にこれをきれいにするために最善を尽くしましたが、助けが必要な場合はお知らせください.
- (RKObjectMapping *)mapMe:(Class)class
{
RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:class];
id classType = objc_getClass([NSStringFromClass(class) UTF8String]);
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(classType, &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
// fprintf(stdout, "%s\n", property_getName(property));
const char *type = property_getAttributes(property);
NSString *typeString = [NSString stringWithUTF8String:type];
NSArray *attributes = [typeString componentsSeparatedByString:@","];
// NSLog(@"attributes = %@", attributes);
NSString *typeAttribute = [attributes objectAtIndex:0];
// NSLog(@"typeAttribute = %@", typeAttribute);
NSString *propertyType = [typeAttribute substringFromIndex:1];
if ([propertyType hasPrefix:@"@"] && [propertyType length] > 1) {
NSString * typeClassName = [propertyType substringWithRange:NSMakeRange(2, [propertyType length]-3)]; //turns @"NSDate" into NSDate
Class typeClass = NSClassFromString(typeClassName);
if (typeClass != nil && ![typeClassName hasPrefix:@"NS"]) {
// my custom class detected.
RKObjectMapping *subMapping = [self mapMe:typeClass forObjectManager:objectManager];
[mapping mapRelationship:[NSString stringWithUTF8String:property_getName(property)] withMapping:subMapping];
[objectManager.mappingProvider setMapping:subMapping forKeyPath:[NSString stringWithUTF8String:property_getName(property)]];
} else {
[mapping addAttributeMapping:[RKObjectAttributeMapping mappingFromKeyPath:[NSString stringWithFormat:@"%@.text", [NSString stringWithUTF8String:property_getName(property)]] toKeyPath:[NSString stringWithUTF8String:property_getName(property)]]];
}
}
}
free(properties);
return mapping;
}
そして、それを自動的にマップするには、次のように呼び出します。
[self mapMe:[Myclass class]];