I see a lot of code references when writing delegates using something likes
@property (nonatomic, weak) id<mySuperCoolDelegate> delegate;
normally where id<mySuperCoolDelegate>
is, is the data type of the property. So the questions are:
Is my understanding correct, that above syntax is telling the compiler data type of the id is mySuperCoolDelegate?
Any other examples where this sort of code (data type specified for id) could be used?
Thanks!
This syntax tells the compiler that
delegate
is of some kind of class (any class) that implements themySuperCoolDelegate
protocol.This allows a certain component to notify another component on some event that happened without the need to know about the notified component (type-wise). (e.g.
UITextView
notifies its controller that the text has been changed without having a reference to that controller, only through the generic-typed delegate so theUITextView
does not need to limit itself to a specific controller's type)Also note that delegates are usually declared as weak (rather than strong). If an instance of
UIViewController
has a strong reference to aUITextView
instance and that text view delegate (assume it is strong) is the controller instance then you will have a retaining cycle where both objects release will be dependent on the other object's release (which will never happen and leave you with a memory leak).This piece of code is objective-c's way of implementing interfaces (as in Java or Go). using "id" means that you don't know at compile time what type of object it will be. But using the protocol in angle brackets you are telling the compiler that no matter what object it will be, it will need to support the 'mySuperCoolDelegate" protocol. If it doesn't - the compiler will let you know.
Short:
This tells the compiler that the property can be of any type as long as it implements the protocol
mySuperCoolDelegate
.Still too short to be 100% accurate but easy to understand:
id
is similar toNSObject*
, meaning it is a reference to any kind of object (not only subclasses of NSObject, to be frank). Witin <> you declare which protocols the object has to conform to.Example: It could be both:
or
Wherever you use that property, the compiler will allow you to access all methods that are declared in the related
@protocol
(most likely in some .h file that you need to#include
).