Skip to content

Instantly share code, notes, and snippets.

@wader
Created September 4, 2012 15:42
Show Gist options
  • Save wader/3622580 to your computer and use it in GitHub Desktop.
Save wader/3622580 to your computer and use it in GitHub Desktop.
NSObject category with method to get class of a property
@interface NSObject (classNameOfPropetyName)
- (Class)classOfPropetyName:(NSString *)propertyName;
@end
@implementation NSObject (classNameOfPropetyName)
- (Class)classOfPropetyName:(NSString *)propertyName {
static NSRegularExpression *re = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// T@"NSString",&,N,Vtest
re = [[NSRegularExpression alloc] initWithPattern:@"@\"([^\"]*)\""
options:0
error:NULL];
});
objc_property_t prop = class_getProperty([self class], [propertyName UTF8String]);
if (prop == NULL) {
return nil;
}
NSString *attrs = [NSString stringWithUTF8String:property_getAttributes(prop)];
NSArray *matches = [re matchesInString:attrs options:0 range:NSMakeRange(0, [attrs length])];
if ([matches count] == 0) {
return nil;
}
NSTextCheckingResult *result = [matches objectAtIndex:0];
if ([result rangeAtIndex:1].location == NSNotFound) {
return nil;
}
return NSClassFromString([attrs substringWithRange:[result rangeAtIndex:1]]);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment