我正在努力学习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];
}
如果使用class_getClassMethod
来获得实例方法的实现,则应该使用class_getInstanceMethod
。
method_exchangeImplementations
仍然以相同的方式使用