我想學習攪拌的概念。方法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];
}
請勿在單元測試和調試之外使用混搭。這既違反了App Store的政策,也會導致非常脆弱的代碼。 – bbum
Swizzling並不反對App Store的政策 - 是否在此評論發表之前?它肯定會導致脆弱的代碼,但它也允許諸如面向方面的代碼(例如:https://github.com/steipete/Aspects)等整潔的東西。 – powerj1984