【问题标题】:Implementing method without conforming protocol不符合协议的实现方法
【发布时间】:2012-05-18 08:39:37
【问题描述】:

在我的 TheTabBarController 中,不符合 UINavigationControllerDelegate 协议,我可以将我的类分配给 moreNavigationController.delegate。

// without conforming to protocol, <UINavigationControllerDelegate>
@interface TheTabBarController : UITabBarController 

self.moreNavigationController.delegate = self;

它只是引发以下警告但编译成功。

从不兼容分配给“id” 输入'TheTabBarController *const __strong'

协议的方法在运行时被调用,没有任何错误。我用它来隐藏一些视图控制器的更多导航栏。

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

所以,我想知道,这是否合法且安全?它会在以后崩溃或泄漏内存吗?这怎么能在语义上被允许呢?运行时如何解决方法,尽管它没有在接口中定义并且协议不符合?或者,UITabBarController 使用了符合协议的隐藏类别?

【问题讨论】:

    标签: objective-c cocoa-touch


    【解决方案1】:

    协议没有运行时意义。它们仅在编译期间用于在您尝试执行您现在正在执行的操作时显示类型错误。如果 TheTabBarController 实现了协议,为什么不希望 UINavigationControllerDelegate 成为 UINavigationControllerDelegate

    在 Objective-C 中,您可以在任何对象上调用任何方法,并且它可以通过实现 forwardInvocation:(NSInvocation *)anInvocation 或相关方法之一来处理它。您还可以在运行时使用objc_install_instance_method 和相关函数向对象或类添加新方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多