Skip to content

Instantly share code, notes, and snippets.

  • Save zykov/2daff15c10f24cec97174c2260974c02 to your computer and use it in GitHub Desktop.
Save zykov/2daff15c10f24cec97174c2260974c02 to your computer and use it in GitHub Desktop.
Objective-C the get property name string for a class and check it at compile-time

A simple idea using the trick of keypath(...) derived from libextobjc and ReactiveCocoa and null-object pattern.

Create a category method in NSObject and define a macro PropertyNameForClass().


NSObject+PropertyName.h:

#import <Foundation/Foundation.h>

#define PropertyNameForClass(Klass, PropertyName) \
        (((void)(NO && ((void)[Klass _nullObjectForFindingPropertyName].PropertyName, NO)), # PropertyName))

#define PropertyStringForClass(Klass, PropertyName) \
        @PropertyNameForClass(Klass, PropertyName)

@interface NSObject (PropertyName)
+ (instancetype)_nullObjectForFindingPropertyName;
@end

NSObject+PropertyName.m:

#import "NSObject+PropertyName.h"

@implementation NSObject (PropertyName)
+ (instancetype)_nullObjectForFindingPropertyName;{
  return nil;
}
@end

Now you can get the property name by the macro and check the property at compile-time without any side effect:

// get C string
char *propertyCString = PropertyNameForClass(AnyClass, key);
// get Objective-C string
NSString *propertyString = @PropertyNameForClass(AnyClass, key);
// or...
NSString *propertyString = PropertyStringForClass(AnyClass, key);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment