从NSDictionary实例化自定义类

从NSDictionary实例化自定义类

本文介绍了从NSDictionary实例化自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个感觉,这是愚蠢的问题,但我会问任何...

I have a feeling that this is stupid question, but I'll ask anyway...

我有一个 NSDictionary 对象的键/值对对应于我创建的自定义类,调用 MyClass 。有一个简单的或最佳实践方法,我基本上做一些像 MyClass * instance = [ map NSDictionary 属性为 MyClass ]; ?我有一种感觉,我需要做一些事情与 NSCoding NSKeyedUnarchiver ,而不是绊倒我自己,

I have a collection of NSDictionary objects whose key/value pairs correspond to a custom class I've created, call it MyClass. Is there an easy or "best practice" method for me to basically do something like MyClass * instance = [map NSDictionary properties to MyClass ];? I have a feeling I need to do something with NSCoding or NSKeyedUnarchiver, but rather than stumble through it on my own, I figure someone out there might be able to point me in the right direction.

推荐答案

-setValuesForKeysWithDictionary:方法,以及 -

The -setValuesForKeysWithDictionary: method, along with -dictionaryWithValuesForKeys:, is what you want to use.

示例:

// 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]];

这篇关于从NSDictionary实例化自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 09:58