Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

objective-c

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?

like image 419
Coocoo4Cocoa Avatar asked Mar 20 '09 03:03

Coocoo4Cocoa


People also ask

What is a protocol in Objective-C?

In Objective-C, a protocol is a group of methods that can be implemented by any class. Protocols are essentially the same as interfaces in C#, and they both have similar goals.

How do instance variables work?

Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.

What is the difference between Swift protocol and Objective-C protocol?

In Swift, calling a method will be decided at compile time and is similar to object-oriented programming, whereas in Objective C, calling a method will be decided at runtime, and also Objective C has special features like adding or replacing methods like on a class which already exists.


1 Answers

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.

like image 160
Peter Hosey Avatar answered Sep 23 '22 20:09

Peter Hosey