0

我看到了这个代码的示例代码:

在 .h 文件中:

  CALayer *_animationLayer;
  @property (nonatomic, retain) CALayer *animationLayer;

在 .m 文件中:

  @synthesize animationLayer = _animationLayer;

我猜它与保留计数有关?

有人可以解释一下吗?

4

2 回答 2

2

将其视为变量名称的别名。

来自可可基础指南

的语法@synthesize还包括一个扩展,允许您为属性及其实例变量存储使用不同的名称。例如,考虑以下语句:

@synthesize title, directReports, role = jobDescrip;

title这告诉计算机合成属性、directReports和 的访问器方法role并使用jobDescrip 实例变量来支持role 属性。

于 2011-03-20T07:44:53.193 回答
1

.h 文件中的代码声明了两件事,一个名为_animationLayerwhich 的 type的变量和一个名为which的 typeCALayer*的属性。.m 文件中的代码指示objective-c 编译器自动为属性生成getter 和setter,使用变量来保存设置的实际值。animationLayerCALayer*animationLayer_animationLayer

例如:

_animationLayer = nil;  //initialize the variable to nil
self.animationLayer = [[CALayer alloc] init];  //assign a value to the property
NSLog("_animationLayer is:  %@", _animationLayer);  //it's not set to nil anymore
_animationLayer = nil;  //set it to nil again
NSLog("self.animationLayer is:  %@", self.animationLayer);  //now the property is nil

你是对的,这确实与对象的 retainCount 有某种关系(因此将变量视为属性的直接别名并不完全正确)。本质上,直接使用_animationLayer变量设置值不会保留新值或释放旧值。使用属性访问器设置值。例如:

_animationLayer = [[CALayer alloc] init];  //retain count is 1
self.animationLayer = nil;                 //retain count is 0

self.animationLayer = [[CALayer alloc] init];  //oops, retain count is 2
self.animationLayer = nil;  //retain count is 1, the object leaked

_animationLayer = [[CALayer alloc] init];  //retain count is 1
[_animationLayer release];               //retain count is 0
self.animationLayer = nil;               //oops, just released it again
于 2011-03-20T07:59:43.347 回答