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

后端 未结 6 936
感情败类
感情败类 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:57

    There are so many solutions and nothing worked for me as I had a complex nested object structure. This solution takes things from Richard and Damien but improvises as Damien's solution is tied to naming keys as class names.

    Here is the header

    @interface NSDictionary (PropertiesOfObject)
    +(NSDictionary *) dictionaryWithPropertiesOfObject:(id)obj;
    @end
    

    Here is the .m file

    @implementation NSDictionary (PropertiesOfObject)
    
    static NSDateFormatter *reverseFormatter;
    
    + (NSDateFormatter *)getReverseDateFormatter {
    if (!reverseFormatter) {
        NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        reverseFormatter = [[NSDateFormatter alloc] init];
        [reverseFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
        [reverseFormatter setLocale:locale];
    }
    return reverseFormatter;
    }
    
     + (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])];
        id object = [obj valueForKey:key];
    
        if (object) {
            if ([object isKindOfClass:[NSArray class]]) {
                NSMutableArray *subObj = [NSMutableArray array];
                for (id o in object) {
                    [subObj addObject:[self dictionaryWithPropertiesOfObject:o]];
                }
                dict[key] = subObj;
            }
            else if ([object isKindOfClass:[NSString class]]) {
                dict[key] = object;
            } else if ([object isKindOfClass:[NSDate class]]) {
                dict[key] = [[NSDictionary getReverseDateFormatter] stringFromDate:(NSDate *) object];
            } else if ([object isKindOfClass:[NSNumber class]]) {
                dict[key] = object;
            } else if ([[object class] isSubclassOfClass:[NSObject class]]) {
                dict[key] = [self dictionaryWithPropertiesOfObject:object];
            }
        }
    
    }
    return dict;
    }
    
    @end
    

提交回复
热议问题