Created
January 22, 2013 21:52
-
-
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.
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 <Foundation/Foundation.h> | |
| @interface NSObject (DCTPropertyNameFromSelector) | |
| - (NSString *)dct_propertyNameForSelector:(SEL)selector; | |
| @end |
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 <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 |
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 <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