以我从未见过的方式保留财产?
我看到了一个带有以下代码的示例代码:
在 .h 文件中:
CALayer *_animationLayer;
@property (nonatomic, retain) CALayer *animationLayer;
在 .m 文件中:
@synthesize animationLayer = _animationLayer;
我猜它与保留计数有关?
有人可以解释一下吗?
I saw a sample code with this code:
in the .h file:
CALayer *_animationLayer;
@property (nonatomic, retain) CALayer *animationLayer;
And in the .m file:
@synthesize animationLayer = _animationLayer;
I am guessing it is related to the retain count?
Can someone explain that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其视为变量名的别名。
来自 Cocoa 基础指南:
Consider it like an alias for the variable name.
From the Cocoa Fundamentals Guide:
.h 文件中的代码声明了两件事,一个名为
_animationLayer
的变量,其类型为CALayer*
,以及一个名为animationLayer
的属性,也是CALayer*
类型。 .m 文件中的代码指示 Objective-C 编译器自动为animationLayer
属性生成 getter 和 setter,使用_animationLayer
变量来保存实际值放。例如:
你是对的,这确实与对象的retainCount有一些关系(因此将变量视为属性的直接别名并不完全正确)。本质上,直接使用
_animationLayer
变量设置值不会保留新值或释放旧值。使用属性访问器设置值即可。例如:The code in the .h file is declaring two things, a variable called
_animationLayer
which is of typeCALayer*
, and a property calledanimationLayer
which is also of typeCALayer*
. The code in the .m file is instructing the objective-c compiler to automatically generate getters and setters for theanimationLayer
property, using the_animationLayer
variable to hold the actual value that is set.So for instance:
And you're correct, this does have some relationship to the object's retainCount (so it's not quite correct to think of the variable as a direct alias for the property). In essence, setting the value directly using the
_animationLayer
variable does not retain the new value or release the old value. Setting the value using the property accessor does. For example: