How should I replace an instance of a class in the system with a subclass in Objective-C?
I have subclassed a system class (UINavigationBar, to be specific) to add some specific functionality. I've been using this 开发者_开发技巧everywhere, as a replacement for UINavigationBar. However, now I want to replace some UINavigationBars used in system frameworks with my custom subclass, so they provide the same behaviour. In specific, I would like the UINavigationBar in the UITabBarController's more view controller to be an instance of my class.
I thought this might be impossible, so I tried creating a category on UINavigationBar, which would propagate everywhere in the system. However, my category would need to do some custom initialisation and teardown (Subscribing and unsubscribing from a NSNotificationCenter's notification). If I overwrite the init/dealloc methods in my category, I won't be able to call the original methods (as implemented by UINavigationBar), which could be very dangerous/fatal/probably not very functional.
One potential solution is method swizzling, but I'm not quite sure how to use it and it could apparently be quite complicated.
If anyone's able to elaborate on how to implement something which would solve my problems (or some custom code for how I could use method swizzling), I'd be very grateful.
You can override the +allocWithZone: method on UINavigationBar class to instead create an instance of your subclass (just as a class cluster behaves), using the method_setImplementation() function (check the Objective-C Runtime Reference for more details of the function)
精彩评论