通过runtime的method_exchangeImplementations(Method m1, Method m2)方法,
可以进行交换方法的实现;一般用自己写的方法来替换系统的方法实现
例如:数组(字典)中不能添加nil,如果添加程序会崩,用自己的方法替换系统防止系统崩溃
下面直接上代码
#import "NSMutableArray+YSExtension.h"
#import <objc/runtime.h>
@implementation NSMutableArray (YSExtension)
+ (void)load {
Method orginalMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:));
Method newMethod = class_getInstanceMethod(NSClassFromString(@"__NSArrayM"), @selector(newAddobject:));
method_exchangeImplementations(orginalMethod, newMethod);
}
- (void)newAddobject:(id)obj {
if (obj != nil) {
[self newAddobject:obj];
}else{
[self newAddobject:@""];
}
}
@end