0

We're making use of Swizzling in Objective-C. For convenience we're using CoconutKit's helper methods to achieve this:

HLSSwizzleSelectorWithBlock_Begin([TMObjectCache class], @selector(objectForKey:))
    ^(TMObjectCache *self, NSString *key) {
        key = nil;
        return ((id (*)(id, SEL, NSString*))_imp)(self, _cmd, key);

    }
HLSSwizzleSelectorWithBlock_End;

We'd like to however also un-swizzle this method after some point in the code. Is there a way to do this?

Gaurav Sharma
  • 2,680
  • 3
  • 26
  • 36

1 Answers1

2

I'm not familiar with CoconutKit, but swizzling is just a call to method_exchangeImplementations(). That function swaps two implementations. So if you call it again with the same parameters, you'll swap the implementations back. You'll need to look at how HLSSwizzleSelectorWithBlock_Begin builds up its call to method_exchangeImplementations() and make it again.

And of course, insert all standard warnings that swizzling is incredibly dangerous, fragile, primarily useful for debugging, and should be strongly avoided in production code if there is any other solution possible.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • "swizzling is incredibly dangerous, fragile, primarily useful for debugging, and should be strongly avoided in production code" Except that Cocoa wlll happily do it to you behind your back. :( – matt Apr 27 '15 at 15:08
  • 1
    Yeah; but the folks who did KVO had access to the source code, and all the Apple devs know not to break KVO. They don't have the same worry about your swizzles. (Of course KVO is isa-swizzling, not method-swizzling. Do you know an Apple-applied method-swizzle that I'm forgetting?) – Rob Napier Apr 27 '15 at 16:15
  • I think KVO was the main one I had in mind; as you say, it isn't method swizzling, but I still regard it with suspicion (though I am compelled to use it). – matt Apr 27 '15 at 16:21
  • 1
    This answer is incomplete. Swizzling does not *necessarily* use `method_exchangeImplementations`. In fact, it's better when it *doesn't*. https://blog.newrelic.com/2014/04/16/right-way-to-swizzle/ – Wayne Nov 09 '17 at 19:37