2015-09-09 46 views
0

下面是我的代码,请帮我找出这个错误的原因是什么。 错误是Objective-C运行时method_exchangeImplementations不起作用

xxx_objectAtIndex:(NSUInteger)指数不工作

代码:

+ (void)load 
{ 
    static dispatch_once_t onceToken; 
    dispatch_once(&onceToken, ^{ 
    Class class = [self class]; 
    /* When swizzling a class method, use the following: */ 
    /* Class class = object_getClass((id)self); */ 

    SEL originalSelector = @selector(objectAtIndex:);/* NSArray's way */ 
    SEL swizzledSelector = @selector(xxx_objectAtIndex:);/* will change way */ 

    Method originalMethod = class_getInstanceMethod(class, originalSelector); 
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector); 
    method_exchangeImplementations(originalMethod, swizzledMethod); 


    }); 
} 
/*but when I use objectAtIndex: not perform this way*/ 
- (id)xxx_objectAtIndex:(NSUInteger)index 
{ 

    NSLog(@"=========1==========="); 
    if (index < self.count) 
    { 
     return [self xxx_objectAtIndex:index]; 
    } 

    return @""; 
} 

回答

0

从NSHipster article鉴于我认为你应该做它用这种方式。

 BOOL didAddMethod = 
      class_addMethod(class, 
       originalSelector, 
       method_getImplementation(swizzledMethod), 
       method_getTypeEncoding(swizzledMethod)); 

     if (didAddMethod) { 
      class_replaceMethod(class, 
       swizzledSelector, 
       method_getImplementation(originalMethod), 
       method_getTypeEncoding(originalMethod)); 
     } else { 
      method_exchangeImplementations(originalMethod, swizzledMethod); 
     } 
+0

当我用你的方式,始终无法执行这样xxx_objectAtIndex: –

+0

在class_getInstanceMethod方法,你使用的类。尝试使用自我。 –

+0

我尝试过,但总是不能这样执行xxx_objectAtIndex:.....为什么.... –