Skip to content

Instantly share code, notes, and snippets.

@youngshook
Created May 30, 2014 15:16
Show Gist options
  • Save youngshook/0c9c3e27f210c7d9bac4 to your computer and use it in GitHub Desktop.
Save youngshook/0c9c3e27f210c7d9bac4 to your computer and use it in GitHub Desktop.
Auto To Object Reflection
#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