Created
May 30, 2014 15:16
-
-
Save youngshook/0c9c3e27f210c7d9bac4 to your computer and use it in GitHub Desktop.
Auto To Object Reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSObject+Reflection.h" | |
#import <objc/runtime.h> | |
@implementation NSObject (Reflection) | |
- (NSArray *)propertyKeys | |
{ | |
unsigned int outCount, i; | |
objc_property_t *properties = class_copyPropertyList([self class], &outCount); | |
NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount]; | |
for (i = 0; i < outCount; i++) { | |
objc_property_t property = properties[i]; | |
NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; | |
[keys addObject:propertyName]; | |
} | |
free(properties); | |
return keys; | |
} | |
- (BOOL)reflectDataFromObject:(NSObject *)dataSource | |
{ | |
BOOL ret = NO; | |
for (NSString *key in [self propertyKeys]) { | |
if ([dataSource isKindOfClass:[NSDictionary class]]) { | |
ret = ([dataSource valueForKey:key] == nil)? NO : YES; | |
} | |
else { | |
ret = [dataSource respondsToSelector:NSSelectorFromString(key)]; | |
} | |
if (ret) { | |
id propertyValue = [dataSource valueForKey:key]; | |
if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue != nil) { | |
[self setValue:propertyValue forKey:key]; | |
} | |
} | |
} | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment