Objective-C – 了解协议引用


// 1.    
TestViewController <TestViewControllerProtocol> *testVC = [TestViewController new];
// 2.
TestViewController *testVC = [TestViewController new];
  1. 上述参考文献之间有什么区别?
  2. 什么时候使用第一个比第二个更可取?

TestViewController.h

@interface TestViewController : UIViewController <TestViewControllerProtocol>
  1. 区别:两者都属于TestViewController型,而只有第一个实现协议TestViewControllerProtocol
  2. 仅当该类未显式符合该协议并且您需要向该协议中定义的该对象发送消息时,才需要第一个。不指定协议并随后发送消息将导致警告或错误。

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

最新更新