Peter Warbo
Peter Warbo

Reputation: 11728

Objective-C – Understanding protocol references

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

// 2.
TestViewController *testVC = [TestViewController new];
  1. What are the differences between the above references?
  2. When would it be preferable to use the first one over the second one?

TestViewController.h

@interface TestViewController : UIViewController <TestViewControllerProtocol>

Upvotes: 0

Views: 72

Answers (1)

fphilipe
fphilipe

Reputation: 10054

  1. Difference: Both are of type TestViewController while only the first one implements the protocol TestViewControllerProtocol.
  2. The first is only needed when that class does not explicitly conform to that protocol and you need to send messages to that object defined in that protocol. Not specifying the protocol and subsequently sending messages would result in a warning or error.

One possible scenario is that you have a superclass TestViewController with multiple subclasses where only a couple of them actually implement that protocol. If you have some code that uses two of those subclasses that both implement the protocol you can easily store a reference to them using the second option.

Upvotes: 1

Related Questions