Created
September 7, 2015 09:40
-
-
Save vikdenic/2ad8cadfd5dd15c856e3 to your computer and use it in GitHub Desktop.
Return array of all properties from a specified object of a particular class type
This file contains hidden or 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 "VZClassHelper.h" | |
| #import <objc/runtime.h> | |
| @implementation VZClassHelper | |
| +(NSMutableArray *)allPropertiesFromObject:(NSObject *)object ofType:(Class)class | |
| { | |
| NSMutableArray *array = [NSMutableArray new]; | |
| unsigned int count=0; | |
| objc_property_t *props = class_copyPropertyList([object class],&count); | |
| for ( int i=0;i<count;i++ ) | |
| { | |
| objc_property_t property = props[i]; | |
| const char * type = property_getAttributes(property); | |
| const char * name = property_getName(property); | |
| NSString *propertyName = [NSString stringWithCString:name encoding:NSUTF8StringEncoding]; | |
| NSString * typeString = [NSString stringWithUTF8String:type]; | |
| NSArray * attributes = [typeString componentsSeparatedByString:@","]; | |
| NSString * typeAttribute = [attributes objectAtIndex:0]; | |
| if ([typeAttribute hasPrefix:@"T@"]) { | |
| NSString * typeClassName = [typeAttribute substringWithRange:NSMakeRange(3, [typeAttribute length]-4)]; //turns @"NSDate" into NSDate | |
| Class typeClass = NSClassFromString(typeClassName); | |
| if (typeClass != nil) { | |
| // Here is the corresponding class even for nil values | |
| if (typeClass == class) | |
| { | |
| NSObject *actualObject = [object valueForKey:propertyName]; | |
| if (actualObject == nil) | |
| { | |
| actualObject = [class new]; | |
| } | |
| [array addObject:actualObject]; | |
| } | |
| } | |
| } | |
| } | |
| NSLog(@"%@", array); | |
| return array; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment