2012-11-14 42 views
0
// 1.  
TestViewController <TestViewControllerProtocol> *testVC = [TestViewController new]; 

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

TestViewController.hObjective-C的 - 理解协议引用

@interface TestViewController : UIViewController <TestViewControllerProtocol> 

回答

1
  1. 差异:两者都是TestViewController类型的,而只有第一个实现协议TestViewControllerProtocol
  2. 第一个只在该类不明确符合该协议时才需要,并且您需要将消息发送到该协议中定义的对象。不指定协议并随后发送消息会导致警告或错误。

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

+0

1.附录中,您可以在接口“TestViewController”中看到始终实现“TestViewControllerProtocol”,所以即使2没有引用该协议,它仍然实现它? –

+0

@PeterWarbo:那么没有什么区别 – newacct

+0

所以第一个是声明它符合协议的方式,而不是在接口中实际做到这一点? –