Instantiating Custom Class from NSDictionary

后端 未结 5 704
-上瘾入骨i
-上瘾入骨i 2021-01-30 09:45

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

I have a collection of NSDictionary objects whose key/value pairs correspond to a cus

5条回答
  •  长情又很酷
    2021-01-30 10:27

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

    Example:

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

提交回复
热议问题