Getting a string value for a property of a class with autocompletion feature and checking it at compile-time is very useful.
This gist demonstrates a simple idea using null-object pattern and the trick of keypath(...)
derived from libextobjc and ReactiveCocoa to get the property name from a class.
Although the compiler should ignore the ((void)(NO && ((void)<#_ObjC_Message_#>, NO))
statement at compile-time, the method +_nullObjectForCheckingPropertyName
still guarantees that the getter method in <#_ObjC_Message_#>
will not be invoked to prevent if from any possible side effect.
Release under MIT.
- Include
NSObject+PropertyName.h
andNSObject+PropertyName.m
in your project. - Get the property name for a class using the macro:
#import "NSObject+PropertyName.h"
@interface AnyClass : NSObject
@property (strong) NSData *data;
@end
// Bad approach (no autocompletion; no compile-time check):
NSString *propertyName = @"data";
// == My approach ==
// C string for a class
keypathForClass(AnyClass, data); // ==> "data"
// NSString for a class
@keypathForClass(AnyClass, data); // ==> @"data"
keypathStringForClass(AnyClass, data); // ==> @"data" (alternative way)
- Get the property name for a protocol using the macro:
#import "NSObject+PropertyName.h"
@protocol AnyProtocol
@property (strong) NSDate *date;
@end
// C string for a protocol
keypathForProtocol(AnyProtocol, date); // ==> "date"
// NSString for a protocol
@keypathForProtocol(AnyProtocol, date); // ==> @"date"
keypathStringForProtocol(AnyProtocol, date); // ==> @"date" (alternative way)
Yes, It's now released under MIT.