利用運行時函數runtime交換2個方法的實現數組
+(void)load //第一次載入內存時候實現load方法 { // class_getInstanceMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>) 對象方法 // class_getClassMethod(<#__unsafe_unretained Class cls#>, <#SEL name#>) 類方法 Method method1 = class_getClassMethod(self, @selector(imageNamed:)); Method method2 = class_getClassMethod(self, @selector(imageWithName:)); method_exchangeImplementations(method1, method2); }
1.保證NSMutableArray addobject對象不爲空函數
+(void)load { //直接[NSMutableArray class] 底層沒法識別 Method method1 = class_getClassMethod(NSClassFromString(@"__NSArrayM"), @selector(hm_addObject:)); Method method2 = class_getClassMethod(NSClassFromString(@"__NSArrayM"), @selector(addObject:)); method_exchangeImplementations(method1, method2); } +(void)wt_addObject:(id)object { if (object != nil) { [self wt_addObject:object]; } }
2.防止數組越界code
+(void)load { Method method1 = class_getClassMethod(NSClassFromString(@"__NSArrayI"), @selector(wt_objectAtIndex:)); Method method2 = class_getClassMethod(NSClassFromString(@"__NSArrayI"), @selector(objectAtIndex:)); method_exchangeImplementations(method1, method2); } +(void)wt_objectAtIndex:(NSUInteger)index { if (index < self.count) { return [self wt_objectAtIndex:index]; }else{ return nil; } }