runtime实现数组中不能添加nil

系统管理员 2021-03-29 14:31 502阅读 0赞

通过runtime的method_exchangeImplementations(Method m1, Method m2)方法,

可以进行交换方法的实现;一般用自己写的方法来替换系统的方法实现

例如:数组(字典)中不能添加nil,如果添加程序会崩,用自己的方法替换系统防止系统崩溃

下面直接上代码

#import “NSMutableArray+YSExtension.h”
#import

@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

发表评论

表情:
评论列表 (有 0 条评论,502人围观)

还没有评论,来说两句吧...

相关阅读