方法Swizzling实现没有发生

时间:2013-07-20 12:41:10

标签: ios objective-c 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];
}

1 个答案:

答案 0 :(得分:1)

您正在使用class_getClassMethod来获取实例方法的实现,您应该使用class_getInstanceMethod

method_exchangeImplementations仍以相同的方式使用