解释@property id< delegateName>的语法 [英] Explaning syntax for @property id<delegateName>
问题描述
@property(nonatomic,weak)id< mySuperCoolDelegate> ;代表;
通常其中 id< mySuperCoolDelegate>
是属性的数据类型。所以问题是:
-
我的理解是否正确,上面的语法告诉编译器的id是mySuperCoolDelegate的数据类型?
-
可以使用这种代码(为id指定的数据类型)的任何其他示例?
谢谢!
此语法告诉编译器 delegate
是某种实现 mySuperCoolDelegate
协议的类(任何类)。
这允许某个组件在发生的某些事件上通知另一个组件,而不需要知道所通知的组件(类型)。 (例如 UITextView
通知其控制器文本已经被更改,而没有引用该控制器,只能通过通用类型的委托,所以 UITextView
不需要限制自己的特定控制器的类型)
还要注意,代理通常被声明为弱(而不是强)。如果一个 UIViewController
的实例对 UITextView
实例和该文本视图委托(假设它很强)有很强的引用,是控制器实例,那么你将有一个保留周期,其中两个对象释放将依赖于另一个对象的释放(这将永远不会发生,并留下一个内存泄漏)。
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 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).
这篇关于解释@property id< delegateName>的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!