我正在努力学习混合的概念。
即使我添加了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 :(得分:1)
您正在使用class_getClassMethod
来获取实例方法的实现,您应该使用class_getInstanceMethod
。
method_exchangeImplementations
仍以相同的方式使用