关于Object-C中的类别:覆盖现有消息

发布于 2024-10-21 13:26:36 字数 809 浏览 6 评论 0原文

类别是子类化的替代方案。如果类别消息已在类中实现,将会发生什么情况。以UIViewController为例,

@implementation UIViewController (Landscape)
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
@end

那么如果我们得到任何扩展UIViewController的XXViewController,默认消息是否会像上面那样实现?

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

正如你所看到的,我的目标是让所有的XXViewController都支持landscape,所以使用category来达到这个目的。

实际上传统的策略会使用子类,并且它是有效的。类别方式怎么样?

谢谢

Category is alternative of subclassing. What will happen if the category message already has been implemented in the class. Take UIViewController as example,

@implementation UIViewController (Landscape)
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
}
@end

So if we get any XXViewController which extends UIViewController, is that the default message will be implemented like above ?

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

As you can see that I aim to make all XXViewController support landscape, so use category to reach this purpose.

Actually the traditional strategy will use subclass, and it works. How about the category way ?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

骷髅 2024-10-28 13:26:36

类别确实可以覆盖方法;您的代码片段完全合法并且应该执行您想要的操作。

但是,您必须小心,就好像两个类别覆盖相同的方法一样,您将得到未定义的结果。另外,如果将来您希望某些视图控制器是纵向的,那么类别可能是一个糟糕的选择。

子类化可能是这里最好的选择。

Categories can indeed override methods; your code snippet is perfectly legal and should do what you want.

You do have to be careful, however, as if 2 categories override the same method you will get undefined results. Also, a category might be a bad choice if in the future you want some view controllers to be portrait.

Subclassing is probably the best option here.

一个人的旅程 2024-10-28 13:26:36

您可能想要使用类集群方法或方法混合。

此处已经介绍了具有类似问题的主题:类别冲突

You may want to use Class Cluster approach, or methods swizzling.

A topic with similar question has been already covered here: Category conflicts

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文