2015-09-09 83 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:.....爲什麼.... –

相關問題