关于Object-C中的类别:覆盖现有消息
类别是子类化的替代方案。如果类别消息已在类中实现,将会发生什么情况。以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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类别确实可以覆盖方法;您的代码片段完全合法并且应该执行您想要的操作。
但是,您必须小心,就好像两个类别覆盖相同的方法一样,您将得到未定义的结果。另外,如果将来您希望某些视图控制器是纵向的,那么类别可能是一个糟糕的选择。
子类化可能是这里最好的选择。
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.
您可能想要使用类集群方法或方法混合。
此处已经介绍了具有类似问题的主题:类别冲突
You may want to use Class Cluster approach, or methods swizzling.
A topic with similar question has been already covered here: Category conflicts