Last active
August 29, 2015 14:13
-
-
Save mpurland/840af77779a29b40b6b6 to your computer and use it in GitHub Desktop.
Objective-C property change macro for better KVO using willChangeValueForKey/didChangeValueForKey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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