Created
August 14, 2018 10:20
-
-
Save wzshare/4b5415095510a00c20b801909e86c5f7 to your computer and use it in GitHub Desktop.
use try catch avoid remove observer more than once
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
#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