5

I'm new to method swizzling and now I'd like to do a little more with that on iOS: Is there an easy/elegant way in Objective-C to redirect all calls of an existing class (ClassA) to another class (ClassB, provided it has the exact same methods). I know it's possible to do so with a single method (method swizzling), but what about an entire class?

  • getting the list of all the class's methods and swizzling them one by one?
  • swizzling only the init method of the class?
  • any other way?

The class I want to replace has a lot of static methods and I don't want to touch the original code.

Bedford
  • 1,136
  • 2
  • 12
  • 36
  • `NSProxy` or you can actually change the ISA pointer of an object so that your instance will become a whole different class. This was done often in mocking, when you could declare a class `B` that extends `A` (therefore having the exact same methods), change some implementation (via an override method) and then swizzle the ISA pointer of an `A` instance for `B`. Usually not a good idea in production code though. – Sulthan Nov 30 '18 at 14:31
  • I'd like to replace the class calls for the entire application, not just for an instance. This class has a lot of static methods, called very often and I'd like to redirect those as well. – Bedford Nov 30 '18 at 14:35
  • 2
    I'm having trouble picturing when this would be easier than just swizzling the individual methods you want to swizzle. If you have to implement every single method of the underlying class, that seems a lot more effort than just swizzling the ones you want (even if it's a lot, it's definitely no more than all of them). As Sulthan notes, this is only useful in exploration and debugging; swizzling is very fragile and should not be used in production code. – Rob Napier Nov 30 '18 at 17:29
  • 2
    BTW, if you want this level of replacement, I'd probably swizzle `+alloc` rather than `-init`. You could also just destroy the original class with `objc_disposeClassPair` and insert your own with the same name with `objc_registerClassPair`. That has to be done before any instances are created of course. (And again, this is incredibly fragile and relies on getting everything just right without necessarily knowing what's going on under the hood. Definitely not for production use.) – Rob Napier Nov 30 '18 at 17:32
  • 1
    You say you want to swizzle a class, then you want to swizzle the entire application. I think it would be helpful to describe *what* you're trying to accomplish. – James Bucanek Nov 30 '18 at 18:35

0 Answers0