Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active December 21, 2017 17:54
Show Gist options
  • Save steipete/6873236 to your computer and use it in GitHub Desktop.
Save steipete/6873236 to your computer and use it in GitHub Desktop.
///////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Warn if we KVO a weak property
// Doesn't support key paths.
static BOOL PSPDFIsWeakProperty(id object, NSString *keyPath) {
objc_property_t property = class_getProperty([object class], keyPath.UTF8String);
if (property) {
// https://developer.apple.com/library/mac/documentation/cocoa/conceptual/objcruntimeguide/articles/ocrtpropertyintrospection.html
const char *attributes = property_getAttributes(property);
return attributes && strstr(attributes, ",W");
}
return NO;
}
// Adding KVO to weak properties is a very bad idea.
// See http://www.componentix.com/blog/28/debug-usage-of-objectivec-weak-properties-with-kvo
__attribute__((constructor)) static void PSPDFWarnOnWeakPropertyKVO(void) {
@autoreleasepool {
SEL selector = NSSelectorFromString(@"pspdf_addObserver:forKeyPath:options:context:");
PSPDFReplaceMethodWithBlock(NSObject.class, @selector(addObserver:forKeyPath:options:context:), selector, ^(NSObject *self, NSObject *observer, NSString *keyPath, NSKeyValueObservingOptions options, void *context) {
if (PSPDFIsWeakProperty(self, keyPath)) {
PSPDFLogError(@"WARNING: observing '%@' property, which is weak and so isn't fully KVO-compliant", keyPath);
}
((void ( *)(id, SEL, NSObject*, NSString*, NSKeyValueObservingOptions, void *))objc_msgSend)(self, selector, observer, keyPath, options, context);
});
}
}
@steipete
Copy link
Author

steipete commented Oct 7, 2013

I only run this on debug builds, saves you from being stupid :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment