2013-07-20 29 views
0

我想學習攪拌的概念。方法Swizzling實現不發生

儘管我已經添加了method_exchangeImplementations,但方法仍未調整。任何想法,我要去哪裏錯了?

#import <objc/runtime.h> 

@interface POCViewController() 

- (void)addSwizzle; 
- (void)originalMethod; 
- (void)swizzledMethod; 

@end 

@implementation POCViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

    //Add swizzle 
    [self addSwizzle]; 

    //Call the original method 
    [self originalMethod]; 
} 

- (void)addSwizzle 
{ 
    Method original, swizz; 

    original = class_getClassMethod([self class], @selector(originalMethod)); 
    swizz = class_getClassMethod([self class], @selector(swizzledMethod)); 
    method_exchangeImplementations(original, swizz); 
} 

- (void)originalMethod 
{ 
    NSLog(@"Inside original method"); 
} 

- (void)swizzledMethod 
{ 
    NSLog(@"Inside swizzled method"); 
    [self swizzledMethod]; 
} 
+0

請勿在單元測試和調試之外使用混搭。這既違反了App Store的政策,也會導致非常脆弱的代碼。 – bbum

+0

Swizzling並不反對App Store的政策 - 是否在此評論發表之前?它肯定會導致脆弱的代碼,但它也允許諸如面向方面的代碼(例如:https://github.com/steipete/Aspects)等整潔的東西。 – powerj1984

回答

1

您正在使用class_getClassMethod得到的實例方法實現,你應該使用class_getInstanceMethod來代替。

method_exchangeImplementations仍然以相同的方式使用

+0

啊!不相信我沒注意到。 非常感謝Wattson。 – footyapps27

+1

不用擔心。調試像這樣的東西的一種方法是,原始的和swizz應該是NULL,通常是一個好跡象出現了錯誤 – wattson12

+0

yep應該已經打印了值。 嘿,你有任何關於轉發調用的線索嗎? – footyapps27