在 Objective-C 中使用子类化可以走多远?
在 iPhone 应用程序中,我需要自定义 UINavigationController 类的外观。 例如,增大栏和字体大小。 我的客户确实需要这个,以及更大的按钮。
因此,我决定对 UINavigationController 进行子类化,而不是从头开始编写该类。 我的问题是,我可以自定义任何方法或属性的默认值吗? 子类化类时有什么限制吗?
In an iPhone app, I need to customize the look of a UINavigationController class. For instance, make the bar and font size bigger. My client really needs that, and bigger buttons aswell.
So, instead of writing the class from scratch, I decided to subclass UINavigationController. My question is, can I customize any method or attribute's default value? Is there any restriction while subclassing a class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这取决于你所说的“限制”是什么意思。 运行时不会阻止您对任何您喜欢的内容进行子类化,但有一些问题。 (虽然你的答案是专门关于 UINavigationController 的,但标题和概念更大,所以我将解决更大的问题。)
@private
的变量,而子类不能访问,与默认的@protected
相比,这是可访问的。在这种情况下,您不从头开始编写类是完全正确的 - 这将是一个坏主意™。 如果您想更改属性(字段?)的默认值,您可以在调用父级初始化程序之后在初始化程序中设置所需的值。 但是,如果您这样做,请确保您没有在父类中存放某些内容,并且始终进行彻底的测试。
Apple 保留了以“_”开头的方法供自己使用,因此我同意 Marc 的警告,不要碰这些方法。 当然,其他一切都是公平的。 :-)
It depends what you mean by "restriction". The runtime will not prevent you from subclassing whatever you like, but there are a few gotchas. (Although your answer is specifically about UINavigationController, the title and concept are bigger, so I'll address the bigger issues.)
@private
and child classes cannot access, versus the default of@protected
, which are accessible.In this case, you're exactly right to not write the class from scratch — that would be a Bad Idea™. If you want to change the default value of an attribute (field?), you can set the desired value in an initializer after calling the parent's initializer. However, if you do this, make sure you're not hosing something in the parent class, and always test thoroughly.
Apple has reserved methods that start with "_" for their own use, so I'd echo Marc's caution to not touch those at all. Everything else is fair game, within reason of course. :-)
不,随意发疯。 许多 Cocoa 类不像其他类那样子类化友好(尤其是那些更多地依赖委托控制的类),并且可能不会公开您需要的功能,但您可以随意子类化任何非私有方法(以 _ 开头)字首)。 如果您确实愿意,您甚至可以对它们进行子类化,尽管在 iPhone 上 Apple 很可能会拒绝您的应用程序。
No, feel free to go nuts. Many Cocoa classes are not as subclassing-friendly as others (especially those that are meant to rely more on delegate control) and may not expose the functionality you need, but you can feel free to subclass any method that's not private (begins with a _ prefix). You could even subclass those if you really wanted to, although on the iPhone chances are Apple would reject your app.