ios - 关于Object-C中的类别: Override existed message

标签 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都支持landscape,所以使用category来达到这个目的。

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

谢谢

最佳答案

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

但是,您必须小心,如果两个类别覆盖相同的方法,您将得到未定义的结果。此外,如果将来您希望某些 View Controller 是纵向的,那么类别可能是一个糟糕的选择。

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

关于ios - 关于Object-C中的类别: Override existed message,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5270411/

相关文章:

ios - 具有降序的 NSSortDescriptor

c# - 在 C# 中从基构造函数调用子类构造函数

objective-c - Objective-C 中结构的扩展

ios - 类别正在实现一个方法,该方法也在主类 : `viewWillAppear:` 中实现

ios - 无法修改 SKSpriteNodes 的 objectAtIndex NSMutableArray

ios - XMPPFramework - 从 Openfire 服务器检索存档消息

ios - 基于 block 的 NSNotificationCenter 观察子类?

ios - 如何指向 allocWithZone : to a subclass under ARC (NOT a singleton!)

swift - 在 Swift 中,Objective-C 类的属性是否有可能满足 Swift @obj 协议(protocol)计算属性要求?

ios - 无法在descriptionForLayoutAttribute_layoutItem_coefficient中创建描述。没什么iOS8