How does a Protocol on an instance variable in Objective-C work?


How does a Protocol on an instance variable in Objective-C work?



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?




Method Syntax in Objective C

1:



Assigning values to Instance variables in Objective C
Close.


Checking For Internet Connectivity in Objective C
It means that aBar will be an instance of a class that conforms to protocol foo.


Do I need to release NSString generated using @“…”?
It could be bar (if that class conformed to foo) or another class that conforms to foo.


Why does using dot-syntax invoke the LHS of this statement twice?
All you know from that declaration is that aBar conforms to the protocol..
How to cast an object in Objective-C
Also, these are only checked at compile-time, not runtime.


Why does Objective-C use YES and NO instead of 1 and 0? [closed]
It is possible to put an object in aBar that is not an instance of a class that conforms to foo.


Objective-C memory management--best practices when returning objects?
But the compiler will warn you about it in most cases..


2:


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.

:).



82 out of 100 based on 42 user ratings 742 reviews