iOS 黑魔法 Method Swizzing 的一个坑

项目中针对使用NSArray的objectAtIndex:函数时,数组越界问题,可以用category配合runtime的黑魔法 Method Swizzing解决。

#import "NSArray+Checking.h"
#import 

@implementation NSArray (Checking)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        Method objAtIndex = class_getInstanceMethod(class, @selector(objectAtIndex:));
        Method objAtIndexCheck = class_getInstanceMethod(class, @selector(objAtIndexCheck:));
        
        BOOL didAddMethod = class_addMethod([self class], @selector(objAtIndexCheck:), method_getImplementation(objAtIndexCheck), method_getTypeEncoding(objAtIndexCheck));
        
        if (didAddMethod) {
            class_replaceMethod([self class], @selector(objAtIndexCheck:), method_getImplementation(objAtIndex), method_getTypeEncoding(objAtIndex));
        } else {
            method_exchangeImplementations(objAtIndex, objAtIndexCheck);
        }
    });
}

- (id)objAtIndexCheck:(NSInteger)index{
    if (self.count <= index) {
        return nil;
    }
    return [self objAtIndexCheck:index];
}

@end

这样当调用【NSArray objectAtIndex:】时,就会先先调用objAtIndexCheck:,然后做一些自己的判断,再去调用系统的函数。

但是问题来了
上面的代码函数objAtIndexCheck:并没有被成功调用,检查了一下午,无数次的验证,仍然没有结果。
我怀疑写法问题?还是这种被广大程序猿吹嘘的方法根本就是错的?
然后我进行了尝试

//在一个类里面这样写。
    Method objAtIndex = class_getInstanceMethod(self.class, @selector(aa));
    Method objAtIndexCheck = class_getInstanceMethod(self.class, @selector(bb));
    
    method_exchangeImplementations(objAtIndex, objAtIndexCheck);

    [self aa];
    [self bb];

完全没有问题。

我问了朋友,朋友给了我一篇文章
作者遇到了和我一样的问题,他进行了如下尝试,也没有问题。(我没测试)

+(void)load{ 
  static dispatch_once_t onceToken ; 
  dispatch_once(&onceToken, ^{ 
    Method m1 = class_getInstanceMethod([self class], @selector(lastObject)); 
    Method m2 = class_getInstanceMethod([self class], @selector(My_lastObject)); 
    BOOL isAdd = class_addMethod([self class], @selector(lastObject), method_getImplementation(m2), method_getTypeEncoding(m2)); 
    if (isAdd == YES) { 
        class_replaceMethod([self class], @selector(My_lastObject), method_getImplementation(m1), method_getTypeEncoding(m1)); 
    }else{ 
        method_exchangeImplementations(m1, m2); 
} 
    Method m3 = class_getInstanceMethod([self class], @selector(firstObject)); 
    Method m4 = class_getInstanceMethod([self class], @selector(My_fistObjcet)); 
    method_exchangeImplementations(m3, m4); 
});
}

-(id)My_fistObjcet{ 
  NSLog(@"My_fistObjcet : exchangeSuccess"); 
  return [self My_fistObjcet];
}

-(id)My_lastObject{ 
  NSLog(@"My_lastObject : exchangeSuccess"); 
  return [self My_lastObject];
}

-------结论------
并不是不支持,而是使用错了类名,对于class_getInstanceMethod函数第一个参数的class,使用的不是[self class],而应该是需要的类alloc init之后的真实类,NSArray对应__NSArrayI,NSMutableArray对应__NSArrayM,而后面的函数class_addMethod、class_replaceMethod使用的则是[self class]。进行如下修改就没问题了

Class class = NSClassFromString(@"__NSArrayI");
Method objAtIndex = class_getInstanceMethod(class, @selector(objectAtIndex:));
Method objAtIndexCheck = class_getInstanceMethod(class, @selector(objAtIndexCheck:));
        
BOOL didAddMethod = class_addMethod([self class], @selector(objAtIndexCheck:), method_getImplementation(objAtIndexCheck), method_getTypeEncoding(objAtIndexCheck));
        
if (didAddMethod) {
    class_replaceMethod([self class], @selector(objAtIndexCheck:), method_getImplementation(objAtIndex), method_getTypeEncoding(objAtIndex));
} else {
    method_exchangeImplementations(objAtIndex, objAtIndexCheck);
}

iOS 黑魔法 Method Swizzing 的一个坑_第1张图片
NSArray Method Swizzing.png

对于OC数组来说,NSArray确实是基类,[NSArray class]是NSArray,但是NSArray *array = [[NSArray alloc] init];之后,这时的array的类就不是NSArray了而是 __NSArrayI。具体为什么不是很清楚,应该是OC的 类簇的问题。

所以先找到实例的具体类,然后再确定参数的class

NSString类.png
/** 
 * Returns a specified instance method for a given class.
 * 
 * @param cls The class you want to inspect.
 * @param name The selector of the method you want to retrieve.
 * 
 * @return The method that corresponds to the implementation of the selector specified by 
 *  \e name for the class specified by \e cls, or \c NULL if the specified class or its 
 *  superclasses do not contain an instance method with the specified selector.
 *
 * @note This function searches superclasses for implementations, whereas \c class_copyMethodList does not.
 */
OBJC_EXPORT Method class_getInstanceMethod(Class cls, SEL name)
    __OSX_AVAILABLE_STARTING(__MAC_10_0, __IPHONE_2_0);



/** 
 * Adds a new method to a class with a given name and implementation.
 * 
 * @param cls The class to which to add a method.
 * @param name A selector that specifies the name of the method being added.
 * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
 * @param types An array of characters that describe the types of the arguments to the method. 
 * 
 * @return YES if the method was added successfully, otherwise NO 
 *  (for example, the class already contains a method implementation with that name).
 *
 * @note class_addMethod will add an override of a superclass's implementation, 
 *  but will not replace an existing implementation in this class. 
 *  To change an existing implementation, use method_setImplementation.
 */
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, 
                                 const char *types) 
     __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

最后同样测试了一下NSString,同样的情况。

#import "NSString+Check.h"
#import 

@implementation NSString (Check)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = NSClassFromString(@"__NSCFConstantString");
        Method objAtIndex = class_getInstanceMethod(class, @selector(isEqualToString:));
        Method objAtIndexCheck = class_getInstanceMethod(class, @selector(isEqualToStringCheck:));
        
        BOOL didAddMethod = class_addMethod([self class], @selector(isEqualToStringCheck:), method_getImplementation(objAtIndexCheck), method_getTypeEncoding(objAtIndexCheck));
        
        if (didAddMethod) {
            class_replaceMethod([self class], @selector(isEqualToStringCheck:), method_getImplementation(objAtIndex), method_getTypeEncoding(objAtIndex));
        } else {
            method_exchangeImplementations(objAtIndex, objAtIndexCheck);
        }
    });
}

- (BOOL)isEqualToStringCheck:(NSString *)aString{
    NSLog(@"aaa = %@",aString);
    return [self isEqualToStringCheck:aString];
}

@end

你可能感兴趣的:(iOS 黑魔法 Method Swizzing 的一个坑)