Objective-C - 理解协议引用

时间:2012-11-14 10:10:50

标签: objective-c cocoa protocols

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

// 2.
TestViewController *testVC = [TestViewController new];
  1. 上述参考文献有何不同之处?
  2. 何时最好使用第一个?第二个?
  3. TestViewController.h

    @interface TestViewController : UIViewController <TestViewControllerProtocol>
    

1 个答案:

答案 0 :(得分:1)

  1. 区别:两者都是TestViewController类型,而只有第一个实现协议TestViewControllerProtocol
  2. 只有当该类没有明确地符合该协议并且您需要向该协议中定义的该对象发送消息时,才需要第一个。未指定协议并随后发送消息将导致警告或错误。
  3. 一种可能的情况是,您有一个具有多个子类的超类TestViewController,其中只有几个实际实现了该协议。如果您有一些代码使用其中两个实现协议的子类,则可以使用第二个选项轻松存储对它们的引用。