我觉得这是个愚蠢的问题,但我还是会问…
我有一个NSDictionary对象的集合,它们的键/值对对应于我创建的自定义类,称之为MyClass。对于我来说,是否有一种简单或“最佳实践”的方法来做一些基本的事情,比如将属性映射到MyClass * instance = [NSDictionary?我有一种感觉,我需要用MyClass];来做点什么,但我不想一个人绊倒,我想可能有人能给我指明正确的方向。

最佳答案

方法-setvaluesforkeyswithdictionary:,以及-dictionarywhithvaluesforkeys:,是您要使用的。
例子:

// In your custom class
+ (id)customClassWithProperties:(NSDictionary *)properties {
   return [[[self alloc] initWithProperties:properties] autorelease];
}

- (id)initWithProperties:(NSDictionary *)properties {
   if (self = [self init]) {
      [self setValuesForKeysWithDictionary:properties];
   }
   return self;
}

// ...and to easily derive the dictionary
NSDictionary *properties = [anObject dictionaryWithValuesForKeys:[anObject allKeys]];

关于iphone - 从NSDictionary实例化自定义类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/830673/

10-12 00:25
查看更多