Skip to content

Instantly share code, notes, and snippets.

@danielctull
Created January 22, 2013 21:52
Show Gist options
  • Select an option

  • Save danielctull/4598816 to your computer and use it in GitHub Desktop.

Select an option

Save danielctull/4598816 to your computer and use it in GitHub Desktop.
Category to give you the name of a property from a selector, will assert that the property exists.
#import <Foundation/Foundation.h>
@interface NSObject (DCTPropertyNameFromSelector)
- (NSString *)dct_propertyNameForSelector:(SEL)selector;
@end
#import <objc/runtime.h>
@implementation NSObject (DCTPropertyNameFromSelector)
- (NSString *)dct_propertyNameForSelector:(SEL)selector {
NSString *string = NSStringFromSelector(selector);
BOOL hasProperty = NO;
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (unsigned int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *propName = property_getName(property);
NSString *propertyName = (propName != NULL) ? [NSString stringWithCString:propName encoding:NSUTF8StringEncoding] : nil;
hasProperty = [propertyName isEqualToString:string];
if (hasProperty) break;
}
free(properties);
NSAssert(hasProperty, @"%@ does not have a property named %@", NSStringFromClass([self class]), string);
return string;
}
@end
#import <Foundation/Foundation.h>
#import "DCTPropertyNameFromSelector.h"
@interface Test : NSObject
@property (copy) NSString *string;
@end
@implementation Test
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
Test *test = [Test new];
NSString *propertyName = [test dct_propertyNameForSelector:@selector(strings)];
NSLog(@"%@", propertyName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment