Obj-C easy method to convert from NSObject with properties to NSDictionary?

后端 未结 6 937
感情败类
感情败类 2020-12-07 17:17

I ran across something that I eventually figured out, but think that there\'s probably a much more efficient way to accomplish it.

I had an object (an NSObject which

6条回答
  •  感情败类
    2020-12-07 17:50

    To complete the method of Richard J. Ross, this one works with NSArray of custom object.

    +(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj
    {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
        unsigned count;
        objc_property_t *properties = class_copyPropertyList([obj class], &count);
    
        for (int i = 0; i < count; i++) {
            NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
            Class classObject = NSClassFromString([key capitalizedString]);
    
            id object = [obj valueForKey:key];
    
            if (classObject) {
                id subObj = [self dictionaryWithPropertiesOfObject:object];
                [dict setObject:subObj forKey:key];
            }
            else if([object isKindOfClass:[NSArray class]])
            {
                NSMutableArray *subObj = [NSMutableArray array];
                for (id o in object) {
                    [subObj addObject:[self dictionaryWithPropertiesOfObject:o] ];
                }
                [dict setObject:subObj forKey:key];
            }
            else
            {
                if(object) [dict setObject:object forKey:key];
            }
        }
    
        free(properties);
        return [NSDictionary dictionaryWithDictionary:dict];
    }
    

提交回复
热议问题