Skip to content

Instantly share code, notes, and snippets.

@wzshare
Created August 14, 2018 10:20
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 wzshare/4b5415095510a00c20b801909e86c5f7 to your computer and use it in GitHub Desktop.
Save wzshare/4b5415095510a00c20b801909e86c5f7 to your computer and use it in GitHub Desktop.
use try catch avoid remove observer more than once
#import "NSObject+TCKVO.h"
#import <objc/runtime.h>
@implementation NSObject (TCKVO)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self switchMethod];
});
}
+ (void)switchMethod {
Class class = [self class];
SEL originalSelector = @selector(removeObserver:forKeyPath:context:);
SEL swizzledSelector = @selector(tc_removeObserver:forKeyPath:context:);
Method originalMethod = class_getClassMethod(class, originalSelector);
Method swizzledMethod = class_getClassMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
- (void)tc_removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath context:(nullable void *)context {
@try {
[self tc_removeObserver:observer forKeyPath:keyPath context:context];
} @catch (NSException *exception) {
NSLog(@"Remove observer more than once.");
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment