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

时间:2011-03-11 08:04:10

标签: ios subclass objective-c-category

类别是子类化的替代方法。如果已在类中实现类别消息,将会发生什么。以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支持格局,因此使用类别来达到此目的。

实际上,传统策略将使用子类,并且它可以工作。类别方式怎么样?

谢谢

2 个答案:

答案 0 :(得分:3)

类别确实可以覆盖方法;你的代码片段是完全合法的,应该做你想要的。

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

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

答案 1 :(得分:1)

您可能希望使用类聚类方法或方法调配。

此处已涵盖了具有类似问题的主题:Category conflicts