将Object编码/解码为Dictionary的最优雅方法是什么?

时间:2009-04-02 18:26:11

标签: objective-c cocoa

有问题的对象包括键/值对,也就是@property。是否有一种优雅的方法将此对象编码/解码为字典?手动拉出每个属性并手动创建字典似乎是一种蛮力。

3 个答案:

答案 0 :(得分:3)

Objective-C的“对象作为字典”支持来自Key-Value Coding

NSArray *myAttributes; // Assume this exists
NSDictionary *dictRepresentation = [object dictionaryWithValuesForKeys:myAttributes];

答案 1 :(得分:3)

它绝对需要是一本字典吗?因为NSKeyedArchiver为您提供了实际存储的密钥行为,而实际上并不是NSDictionary - 并且还有额外的好处,它可以归档许多属性列表序列化不会自动支持的对象。在CocoaDev wiki上有一个很好的using archivers and unarchivers描述。

答案 2 :(得分:1)

如果您想要的键是相关类的ObjC-2.0属性,您可以执行类似以下操作:

// Assume MyClass exists
unsigned int count = 0;
objc_property_t *properties = class_copyPropertyList([myClassInstance class], &count);
NSMutableDictionary *propertiesDict = [NSMutableDictionary dictionary];
unsigned int i;
for(i = 0; i < count; ++i) {
  NSString *propertyName = [NSString stringWithCString:property_getName(properties[i]) encoding:NSASCIIStringEncoding];
  id propertyValue = [self valueForKey:propertyName];
  if(propertyValue)
    [propertiesDict setObject:propertyValue forKey:propertyName];
}
free(properties), properties = NULL;
// Do something with propertiesDict

这也可以是一个简单的类扩展。

相关问题