// 1.
TestViewController <TestViewControllerProtocol> *testVC = [TestViewController new];
// 2.
TestViewController *testVC = [TestViewController new];
- 上述引用文献之间有什么区别?
- 什么时候使用第一个比第二个更好?
TestViewController.h
@interface TestViewController : UIViewController <TestViewControllerProtocol>
最佳答案
- 区别:两者都是
TestViewController
类型,而只有第一个实现了TestViewControllerProtocol
协议(protocol)。 - 仅当该类未明确符合该协议(protocol)并且您需要向该协议(protocol)中定义的对象发送消息时才需要第一个。不指定协议(protocol)并随后发送消息将导致警告或错误。
一种可能的情况是,您有一个带有多个子类的父类(super class) TestViewController
,其中只有几个子类实际实现该协议(protocol)。如果您有一些代码使用两个都实现该协议(protocol)的子类,您可以使用第二个选项轻松存储对它们的引用。
关于Objective-C – 理解协议(protocol)引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13376756/