Skip to content

Instantly share code, notes, and snippets.

@mpurland
Last active August 29, 2015 14:13
Show Gist options
  • Save mpurland/840af77779a29b40b6b6 to your computer and use it in GitHub Desktop.
Save mpurland/840af77779a29b40b6b6 to your computer and use it in GitHub Desktop.
Objective-C property change macro for better KVO using willChangeValueForKey/didChangeValueForKey
// Note: This requires libextobjc: https://github.com/jspahrsummers/libextobjc
inline static void propertyChangeObject(NSObject *object, NSString *keypath, void (^block)()) {
[object willChangeValueForKey: keypath];
block();
[object didChangeValueForKey: keypath];
}
#define propertyChange(__KEY, block) propertyChangeObject(self, @keypath(self.__KEY), block)
#define propertyChange2(keypath, block) propertyChangeObject(self, keypath, block)
// Examples:
propertyChange(propertyName, ^{
// propertyName is checked at compile-time for object self
});
propertyChange2(@keypath(self.propertyName), ^{
// propertyName is checked at compile-time for the given keypath using @keypath macro
});
propertyChange2(@"propertyName", ^{
// WARNING: This works too...but propertyName is not checked to belong to self.
});
// The first two examples above are better than the following:
[self willChangeValueForKey: @"propertyName"];
// Do something...
[self didChangeValueForKey: @"propertyName"];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment