public
Last active

List declared properties for an Objective-C class

  • Download Gist
objcprops.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
#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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.