Nick
Nick

Reputation: 19684

Objective-C method_exchangeImplementations is not working

I am trying to use the objc runtime library to swap method implementations. I have this simple example but it doesn't seem to work (the implementations are not swapped). What have I forgotten?

    #import "AppDelegate.h"
    #import "MainViewController.h"
    #import <objc/runtime.h>

    @implementation AppDelegate

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        //lowercase NSString Method
        Method originalMethod = class_getInstanceMethod([NSString class], @selector(lowercaseString));
        //uppercase NSString Method
        Method swappedMethod = class_getClassMethod([NSString class], @selector(uppercaseString));
        //swap em
        method_exchangeImplementations(swappedMethod, originalMethod);

        NSLog(@"%@",[@"test" lowercaseString]); //OUTPUT: test !!
        ...
        return YES;
    }

Upvotes: 1

Views: 2156

Answers (2)

Kevin Delord
Kevin Delord

Reputation: 2558

I had a similar problem. the selector wasn't valid, I had to add a .class call.

class_getClassMethod(self.class, @selector(imageNamed:));

Upvotes: 0

Caleb
Caleb

Reputation: 125007

-upperCaseString is an instance method, not a class method. So your call here:

Method swappedMethod = class_getClassMethod([NSString class], @selector(uppercaseString));

is likely returning nil. I'm not sure what method_exchangeImplementations does when one of the arguments is nil, but it's probably not what you're hoping for in any case.

Upvotes: 2

Related Questions