多次删除KVO崩溃
2019-03-15 本文已影响0人
逍遥庄主
有时候回忘记多次添加删除kvo的监听,回出现catch
单个处理
利用@try{self removeObserver:self forKeyPath:@"name"}@catch(NSException *exception){nslog(@"多次删除")}
通用方法使用runtime
代码
.m文件
#import "NSObject +XYKVO.h"
#import<objc/runtime.h>
@implementation NSObject (XYKVO)
+ (void)load {
[self switchMethod];
}
- (void) switchMethod {
SEL removeSel = @selector(removeObserver:forKeyPath:);
SEL xyRemoveSel = @selector(removeXYKVO:forKeyPath:);
Method systemRemoveMethod = class_getClassMethod([self class], removeSel);
Method xyRemoveMethod = class_getClassMethod([self class], myRemoveSel);
method_exchageImplementations(systemRemoveMethod, xyRemoveMethod);
}
- (void) removeXYKVO:(NSObject *)observer forKeyPath:(NSString*)keyPath {
@try {
[self removeXYKVO:observer forKeyPath:keyPath];
} @catch (NSException *exception) {nslog(@"多次删除")}
}