0

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];
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
footyapps27
  • 3,982
  • 2
  • 25
  • 42
  • Don't use swizzling outside of unit tests and debugging. It is both against App Store policy and it'll lead to horribly fragile code. – bbum Jul 20 '13 at 13:31
  • Swizzling isn't against App Store policy - was it before when this comment was made? It can certainly lead to fragile code, but it also allows neat things like Aspect oriented code (for example: https://github.com/steipete/Aspects). – powerj1984 Aug 10 '15 at 01:39

1 Answers1

1

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

wattson12
  • 11,176
  • 2
  • 32
  • 34
  • Ah!!Cant believe I did not notice that. Thanks a lot Wattson. – footyapps27 Jul 20 '13 at 12:54
  • 1
    no worries. one way to debug things like this is that original and swizz would have been NULL, usually a good sign something has gone wrong – wattson12 Jul 20 '13 at 12:57
  • yep should have printed the values. hey, you have any clue about forward invocation as well? – footyapps27 Jul 20 '13 at 13:04
  • as in NSProxy? i haven't used it much, do you mean when combined with swizzling, or as an alternative? – wattson12 Jul 20 '13 at 13:06
  • Na, as in forwardinvocation & methodForSignature methods. Nonetheless thanks for the help mate!! – footyapps27 Jul 20 '13 at 13:07
  • i don't know too much about that but [mike ash](http://www.mikeash.com/pyblog/friday-qa-2009-03-27-objective-c-message-forwarding.html) is usually a good source for in-depth topics – wattson12 Jul 20 '13 at 17:04