我应该如何用 Objective-C 中的子类替换系统中类的实例?
我对系统类(具体来说是 UINavigationBar)进行了子类化,以添加一些特定的功能。我一直在到处使用它,作为 UINavigationBar 的替代品。但是,现在我想用我的自定义子类替换系统框架中使用的一些 UINavigationBar,因此它们提供相同的行为。具体来说,我希望 UITabBarController 的更多视图控制器中的 UINavigationBar 成为我的类的实例。
我认为这可能是不可能的,所以我尝试在 UINavigationBar 上创建一个类别,它将在系统中的任何地方传播。但是,我的类别需要进行一些自定义初始化和拆卸(订阅和取消订阅 NSNotificationCenter 的通知)。如果我覆盖类别中的 init/dealloc 方法,我将无法调用原始方法(由 UINavigationBar 实现),这可能非常危险/致命/可能不太实用。
一种潜在的解决方案是方法调配,但我不太确定如何使用它,而且它显然可能非常复杂。
如果有人能够详细说明如何实现可以解决我的问题的东西(或者一些关于如何使用方法调配的自定义代码),我将非常感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 method_setImplementation() 函数覆盖 UINavigationBar 类上的 +allocWithZone: 方法,以创建子类的实例(就像类簇的行为一样)(检查 Objective-C 运行时参考了解该功能的更多详细信息)
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)