Skip to content

Instantly share code, notes, and snippets.

@holtwick
Last active June 21, 2018 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save holtwick/27321fa97231fcba3ea3fb8621517865 to your computer and use it in GitHub Desktop.
Save holtwick/27321fa97231fcba3ea3fb8621517865 to your computer and use it in GitHub Desktop.
Autocomplete and refactoring compatible keyPaths: https://holtwick.de/blog/keypath-refatoring
// (C)opyright 2018-06-20 Dirk Holtwick, holtwick.it. All rights reserved.
#import <Foundation/Foundation.h>
#define keyPath(k) YES ? @#k : (k ? @"": nil)
#define keyPathFromObject(o, k) YES ? @#k : ((o ?: o.k) ? @"" : nil)
@interface Sample : NSObject
@property id greeting;
@end
@implementation Sample
@end
@interface Demo : NSObject
@property Sample *sample;
@end
@implementation Demo
- (instancetype)init {
self = [super init];
if (self) {
self.sample = [[Sample alloc] init];
self.sample.greeting = @"Hello World";
id akp = keyPath(self.sample.greeting);
id a = [self valueForKeyPath:akp];
NSLog(@"Result: %@ = %@", akp, a);
id bkp = keyPathFromObject(self.sample, greeting);
id b = [self.sample valueForKeyPath:bkp];
NSLog(@"Result: %@ = %@", bkp, a);
NSAssert([a isEqualToString:b], @"Same");
}
return self;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
[[Demo alloc] init];
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment