tags:

views:

633

answers:

2

I see a lot of code such as the following as of late:

id<foo> aBar;

Typically this is something I'd see in a class declaration, such as:

@interface bar : UIViewController <UITableViewDelegate, UITableViewDataSource>

Does the above mean that aBar might be an instance of class bar and promises to have all of the methods declared in the foo protocol?

A: 

Exactly. Protocols mean you do not inherit the class but gets the method prototypes of that class. This way you will know what the method stubs are when you are trying to interact with a object that requires those methods. Think of a shallow Interface in C#.

I say C# because that is my primary language. :)

Tacoman667
+10  A: 

Close. It means that aBar will be an instance of a class that conforms to protocol foo. It could be bar (if that class conformed to foo) or another class that conforms to foo. All you know from that declaration is that aBar conforms to the protocol.

Also, these are only checked at compile-time, not runtime. It is possible to put an object in aBar that is not an instance of a class that conforms to foo. But the compiler will warn you about it in most cases.

Peter Hosey
It think there may be some swapped 'foo' and 'bar' in the question and answer. His class 'bar' doesn't adopt the foo protocol, so the compiler would complain about storing an instance of 'bar' to 'aBar' as it is written.
Quinn Taylor
I don't think there was any swappage, but you're right about the bar class not conforming to the foo protocol. I think his last paragraph explains why he wrote it that way, though.
Peter Hosey