Explaning syntax for @property id

2019-03-01 11:01发布

问题:

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:

  1. Is my understanding correct, that above syntax is telling the compiler data type of the id is mySuperCoolDelegate?

  2. Any other examples where this sort of code (data type specified for id) could be used?

Thanks!

回答1:

This syntax tells the compiler that delegate is of some kind of class (any class) that implements the mySuperCoolDelegate 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 the UITextView 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 a UITextView 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).



回答2:

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.



回答3:

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 to NSObject*, 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:

@interface mySuperCoolClass : <mySuperCoolDelegate> ... @end 

or

@interface somebodyElsesSuperCoolClass : <mySuperCoolDelegate> ... @end 

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).