以下是关于增加接口部分中NSMutableArray类型变量的d保留计数值的程序。
@property (nonatomic, retain) NSMutableArray *dataArray;
实施部分
NSLog(@"%d",[self.dataArray retainCount]);
self.dataArray = [[NSMutableArray alloc] init];
NSLog(@"%d",[self.dataArray retainCount]);
现在在第一行它的显示保留计数值是NSLog内部的O,但是当我们分配数组时,它将保留计数增加到2.我没有明白这一点,为什么保留计数增加到2而不是1。请帮我理解这一点。
答案 0 :(得分:1)
答案 1 :(得分:1)
只有在覆盖getter / setter方法时才应使用_object。 “_object =”只是分配,而“self.object =”则调用其setter方法。您必须使用_object来防止和使用setter方法管理保留计数。 通过编写代码来检查区别:
@property (nonatomic, retain) NSMutableArray *arr;
//=============Accessing with _object==========
NSLog(@"Retain Count before Allocation => %lu", (unsigned long)_arr.retainCount);
_arr = [NSMutableArray arrayWithArray:@[@"arrobj1", @"arrObj3"]];
NSLog(@"Retain Count before Allocation => %lu", (unsigned long)_arr.retainCount);
_arr = [[NSMutableArray alloc] init];
NSLog(@"Retain Count After alloc+init => %lu", (unsigned long)_arr.retainCount);
//============================================
Output is :
Retain Count before Allocation => 0
Retain Count before Allocation => 1
Retain Count After alloc+init => 1
###### And also with accessing objects with self.object#######
//=============Accessing with _object==========
NSLog(@"Retain Count before Allocation => %lu", (unsigned long)self.arr.retainCount);
self.arr = [NSMutableArray arrayWithArray:@[@"arrobj1", @"arrObj3"]];
NSLog(@"Retain Count before Allocation => %lu", (unsigned long)self.arr.retainCount);
self.arr = [[NSMutableArray alloc] init];
NSLog(@"Retain Count After alloc+init => %lu", (unsigned long)self.arr.retainCount);
//============================================
Output is:
Retain Count before Allocation => 0
Retain Count before Allocation => 2
Retain Count After alloc+init => 2
我希望这会对你有所帮助。
答案 2 :(得分:0)
alloc init创建一个保留的实例+1。然后保留的属性在赋值+2上添加一个保留。要获得一个保留计数,a)使用ARC和一个强大的属性,它将为您插入一个版本b)创建一个未保留的实例:
self.dataArray = [NSMutableArray array];
或c)明确自动释放:
self.dataArray = [[[NSMutableArray alloc] init] autorelease];
答案 3 :(得分:0)
由于属性的setter也被调用
self.dataArray = [[NSMutableArray alloc] init];
保留计数被推升至2。
你也可以试试这个
NSMutableArray *temp=[[NSMutableArray alloc]init];
self.dataArray = temp;
[temp release];
释放呼吁临时平衡额外的保留。