代码之家  ›  专栏  ›  技术社区  ›  Keith Fitzgerald

将对象编码/解码为字典最优雅的方法是什么?

  •  2
  • Keith Fitzgerald  · 技术社区  · 17 年前

    所讨论的对象由键/值对aka@property组成。有没有一种优雅的方法可以将这个对象编码/解码成字典?手动拉出每个属性并手工创建字典似乎是一种蛮力。

    3 回复  |  直到 17 年前
        1
  •  3
  •   user23743    17 年前

    它绝对需要一本字典吗?因为 NSKeyedArchiver 提供按键行为存储的纪念品,而实际上不是 NSDictionary -还有一个额外的好处是,它可以存档许多属性列表序列化不自动支持的对象。有一个很好的描述 using archivers and unarchivers 在Cocadev维基上。

        2
  •  3
  •   Chuck    17 年前

    Objective-C的“Object as Dictionary”支持 Key-Value Coding :

    NSArray *myAttributes; // Assume this exists
    NSDictionary *dictRepresentation = [object dictionaryWithValuesForKeys:myAttributes];
    
        3
  •  1
  •   sbooth    17 年前

    如果您想要的键是相关类的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
    

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