Created
November 19, 2012 22:03
-
-
Save mdippery/4114351 to your computer and use it in GitHub Desktop.
List declared properties for an Objective-C class
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 <Foundation/Foundation.h> | |
#import <objc/runtime.h> | |
@interface NSObject (DeclaredProperties) | |
- (NSArray *)properties; | |
@end | |
@interface TestClass : NSObject | |
@property (readonly) NSString *prop1; | |
@property (readonly) NSNumber *prop2; | |
@property (readonly) NSArray *prop3; | |
@end | |
@implementation NSObject (DeclaredProperties) | |
- (NSArray *)properties | |
{ | |
NSMutableArray *propList = [NSMutableArray array]; | |
unsigned int numProps = 0; | |
unsigned int i = 0; | |
objc_property_t *props = class_copyPropertyList([TestClass class], &numProps); | |
for (i = 0; i < numProps; i++) { | |
NSString *prop = [NSString stringWithUTF8String:property_getName(props[i])]; | |
[propList addObject:prop]; | |
} | |
return [[propList copy] autorelease]; | |
} | |
@end | |
@implementation TestClass | |
- (NSString *)prop1 | |
{ | |
return @"prop1"; | |
} | |
- (NSNumber *)prop2 | |
{ | |
return [NSNumber numberWithInteger:2]; | |
} | |
- (NSArray *)prop3 | |
{ | |
return [NSArray arrayWithObject:@"prop3"]; | |
} | |
@end | |
int main(int argc, char **argv) | |
{ | |
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; | |
TestClass *t = [[TestClass alloc] init]; | |
NSLog(@"Properties: %@", [t properties]); | |
[t release]; | |
[pool release]; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment