Last active
December 21, 2017 17:54
-
-
Save steipete/6873236 to your computer and use it in GitHub Desktop.
This file contains 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
/////////////////////////////////////////////////////////////////////////////////////////// | |
#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); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I only run this on debug builds, saves you from being stupid :)