Instantiating Custom Class from NSDictionary

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

    There is no allKeys on NSObject. You'll need to create an extra category on NSObject like below:

    NSObject+PropertyArray.h

    @interface NSObject (PropertyArray)
    - (NSArray *) allKeys;
    @end
    

    NSObject+PropertyArray.m

    #import 
    
    @implementation NSObject (PropertyArray)
    - (NSArray *) allKeys {
        Class clazz = [self class];
        u_int count;
    
        objc_property_t* properties = class_copyPropertyList(clazz, &count);
        NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i < count ; i++) {
            const char* propertyName = property_getName(properties[i]);
            [propertyArray addObject:[NSString  stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        }
        free(properties);
    
       return [NSArray arrayWithArray:propertyArray];
    }
    @end
    

    Example:

    #import "NSObject+PropertyArray.h"
    
    ...
    
    MyObject *obj = [[MyObject alloc] init];
    obj.a = @"Hello A";  //setting some values to attributes
    obj.b = @"Hello B";
    
    //dictionaryWithValuesForKeys requires keys in NSArray. You can now
    //construct such NSArray using `allKeys` from NSObject(PropertyArray) category
    NSDictionary *objDict = [obj dictionaryWithValuesForKeys:[obj allKeys]];
    
    //Resurrect MyObject from NSDictionary using setValuesForKeysWithDictionary
    MyObject *objResur = [[MyObject alloc] init];
    [objResur setValuesForKeysWithDictionary:objDict];
    

提交回复
热议问题