Objective-C – 理解协议(protocol)引用

标签 objective-c cocoa protocols

// 1.    
TestViewController <TestViewControllerProtocol> *testVC = [TestViewController new];

// 2.
TestViewController *testVC = [TestViewController new];
  1. 上述引用文献之间有什么区别?
  2. 什么时候使用第一个比第二个更好?

TestViewController.h

@interface TestViewController : UIViewController <TestViewControllerProtocol>

最佳答案

  1. 区别:两者都是 TestViewController 类型,而只有第一个实现了 TestViewControllerProtocol 协议(protocol)。
  2. 仅当该类未明确符合该协议(protocol)并且您需要向该协议(protocol)中定义的对象发送消息时才需要第一个。不指定协议(protocol)并随后发送消息将导致警告或错误。

一种可能的情况是,您有一个带有多个子类的父类(super class) TestViewController,其中只有几个子类实际实现该协议(protocol)。如果您有一些代码使用两个都实现该协议(protocol)的子类,您可以使用第二个选项轻松存储对它们的引用。

关于Objective-C – 理解协议(protocol)引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376756/

相关文章:

分配初始值设定项的 Cocoa 命名方案

swift - 符合通用协议(protocol)的多个实例

swift - 类不符合协议(protocol)。为什么?

ios - 为什么 tableView :cellForRowAtIndexPath: and tableView:heightForRowAtIndexPath: do not belong to the same protocol?

iOS App 找不到框架头文件

iphone - 单击自定义单元格按钮获取节号和行号?

objective-c - 仅展开 NSOutlineView 中的根节点

iphone - NSManagedObjectContext 没有正确刷新

iphone - 按钮设置突出显示不起作用

c - 在 C 中处理时区