2011-11-07 53 views
2

Iam将NSDictionary发布到JSON webservice以将我的数据保存回本地数据库。什么是将Objective C类转换为NSDictionaries的最佳方式?Objective C class to NSDictionary

这里是我当前的代码,除了从写一个更宽泛的版本,这是最好的方法/只做到这一点?并且包括<obj/runtime.h>可以用苹果吗?

- (NSDictionary*)dictionaryFromContact { 

     Class contactClass = [self class]; 
     u_int count; 

     objc_property_t *properties = class_copyPropertyList(contactClass, &count); 

     NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:count]; 

     for (int i = 0; i<count; i++) { 
      NSString *str = [NSString stringWithCString:property_getName(properties[i]) 
               encoding:NSUTF8StringEncoding]; 

      //Set the dicationary values from our properties 
      [dict setValue:[self valueForKey:str] forKey:str]; 
     } 
     free(properties); 

     return [dict autorelease]; 
    } 

谢谢!

回答

3

class_copyPropertyList是合法的。您可以考虑使用dictionaryWithValuesForKeys:作为快捷方式。

如果您使用本地数据库的Core Data,则应使用attributesByNamerelationshipsByNamepropertiesByName

0

看一看的RestKitObject Mapping功能,它可能会做你的需要。

+0

Restkit很难实现!另外它有很多问题。在最终使v0.10正常工作后,升级到v0.20是一件非常痛苦的事情,我放弃了它并编写了自己的解析器。我不会推荐RestKit。 – Khattab