Instantiating Custom Class from NSDictionary

后端 未结 5 700
-上瘾入骨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:13

    Assuming that your class conforms to the Key-Value Coding protocol, you could use the following: (defined as a category on NSDictionary for convenience):

    // myNSDictionaryCategory.h:
    @interface NSDictionary (myCategory)
    - (void)mapPropertiesToObject:(id)instance
    @end
    


    // myNSDictionaryCategory.m:
    - (void)mapPropertiesToObject:(id)instance
    {
        for (NSString * propertyKey in [self allKeys])
        {
            [instance setValue:[self objectForKey:propertyKey]
                        forKey:propertyKey];
        }
    }
    

    And here's how you would use it:

    #import "myNSDictionaryCategory.h"
    //...
    [someDictionary mapPropertiesToObject:someObject];
    

提交回复
热议问题