天天看點

runtime實作數組中不能添加nil

通過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

轉載于:https://www.cnblogs.com/lcl15/p/7417688.html

繼續閱讀