runtime 交换方法应用

解决数组添加空值崩溃

#import "NSMutableArray+Extension.h"
#import 

@implementation NSMutableArray (Extension)

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class cls = NSClassFromString(@"__NSArrayM");
        Method addMethod = class_getInstanceMethod(cls, @selector(addObject:));
        Method changeAddMethod = class_getInstanceMethod(cls, @selector(xsy_addObject:));
        method_exchangeImplementations(addMethod, changeAddMethod);
        
        Method insertMetod = class_getInstanceMethod(cls, @selector(insertObject:atIndex:));
        Method changeInsertMethod = class_getInstanceMethod(cls, @selector(xsy_insertObject:atIndex:));
        method_exchangeImplementations(insertMetod, changeInsertMethod);
    });
    
    
}

- (void)xsy_addObject:(id)anObject {
    if (anObject == nil) {
        NSLog(@"小子,你敢往里添加空值");
        return;
    }
    [self xsy_addObject:anObject];
}



- (void)xsy_insertObject:(id)anObject atIndex:(NSUInteger)index {
    if (anObject == nil) {
        NSLog(@"小子,你敢往第%lu个元素里添加空值",(unsigned long)index);
        return;
    }
    [self xsy_insertObject:anObject atIndex:index];
}

@end

解决字典添加空值崩溃

#import "NSMutableDictionary+Extection.h"
#import 

@implementation NSMutableDictionary (Extection)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class mcls = NSClassFromString(@"__NSDictionaryM");
        Method setMethod = class_getInstanceMethod(mcls, @selector(setObject:forKeyedSubscript:));
        Method changeSetMethod = class_getInstanceMethod(mcls, @selector(xsy_setObject:forKeyedSubscript:));
        method_exchangeImplementations(setMethod, changeSetMethod);
        
    });
}

- (void)xsy_setObject:(id)obj forKeyedSubscript:(id)key {
    if (obj == nil) {
        NSLog(@"%@对应的值为nil",key);
        return;
    }
    [self xsy_setObject:obj forKeyedSubscript:key];
}

@end

监控点击事件

#import "UIControl+Extection.h"
#import 

@implementation UIControl (Extection)

+ (void)load {
    Method method = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method changeMethod = class_getInstanceMethod(self, @selector(xsy_sendSendAction:to:forEvent:));
    method_exchangeImplementations(method, changeMethod);
    
}

- (void)xsy_sendSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    NSLog(@"%@-%@-%@",NSStringFromSelector(action), target, event);
    [self xsy_sendSendAction:action to:target forEvent:event];
}

@end

你可能感兴趣的:(runtime 交换方法应用)