类别是子类化的替代方法。如果类别消息已在类中实现,将会发生什么情况。以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来达到这个目的。
实际上传统的策略会使用子类,并且它是有效的。类别方式怎么样?
谢谢
最佳答案
类别确实可以覆盖方法;您的代码片段完全合法,并且应该执行您想要的操作。
但是,您必须小心,如果两个类别覆盖相同的方法,您将得到未定义的结果。此外,如果将来您希望某些 View Controller 是纵向的,那么类别可能是一个糟糕的选择。
子类化可能是最好的选择。
关于ios - 关于Object-C中的类别: Override existed message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5270411/