سؤال

I am trying to learn the concept of swizzling.

Even though I have added method_exchangeImplementations, still the methods are not being swizzled. Any idea as to where I am going wrong?

#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];
}
هل كانت مفيدة؟

المحلول

You are using class_getClassMethod to get implementations of instance methods, you should use class_getInstanceMethod instead.

method_exchangeImplementations is still used the same way

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top