Objective-C Tips & Trick - Prioregroup.com
[Objective-C] Set property values ​​from a NSDictionary
       
back

//
//  NSObject+NSDictionary.h
//
@interface NSObject (NSDictionary)
- (void)setValuesWithDictionary:(NSDictionary*)dict;
@end

//
//  NSObject+NSDictionary.m
//
#import "NSObject+NSDictionary.h"
#import <objc/runtime.h>
@implementation NSObject (NSDictionary)
- (void)setValuesWithDictionary:(NSDictionary*)dict
{
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([self class], &count);
    for (int i = 0; i < count; ++i) {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding];
        if ([dict.allKeys indexOfObject:name] != NSNotFound) {
            NSArray *propertyAttributes = [[[[NSString alloc] initWithUTF8String:property_getAttributes(property)] autorelease] componentsSeparatedByString:@","];
            if ([propertyAttributes indexOfObject:@"R"] == NSNotFound) {
                if ([propertyAttributes indexOfObject:@"T@\"NSString\""] != NSNotFound) {
                    [self setValue:[dict objectForKey:name] forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Ti"] != NSNotFound) { // integer
                    [self setValue:@([[dict objectForKey:name] integerValue]) forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Tf"] != NSNotFound) { // float
                    [self setValue:@([[dict objectForKey:name] floatValue]) forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Td"] != NSNotFound) { // double
                    [self setValue:@([[dict objectForKey:name] doubleValue]) forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Tl"] != NSNotFound) { // long
                    [self setValue:@([[dict objectForKey:name] longValue]) forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Ts"] != NSNotFound) { // short
                    [self setValue:@([[dict objectForKey:name] shortValue]) forKey:name];
                } else if ([propertyAttributes indexOfObject:@"Tc"] != NSNotFound) { // bool YES/NO (char ???)
                    [self setValue:@([[dict objectForKey:name] boolValue]) forKey:name];
                }
            }
        }
    }
    free(properties);
}
@end






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com