我在以下代码中收到来自Instruments的报告内存泄漏:
NSArray *array = [[NSArray alloc] initWithObjects:@"Amount (oz):", @"Amount (ml):", @"Supplement:", nil];
self.fieldLabels = array;
[array release];
fieldLabels是一个iVar,声明为:
NSArray *fieldLabels;
@property (nonatomic, retain) NSArray *fieldLabels;
仪器报告如下:
# Category Event Type Timestamp RefCt Address Size Responsible Library Responsible Caller
0 __NSArrayI Malloc 00:16.513.592 1 0x660bb40 32 InfantCare -[Supplemental_Amount viewDidLoad]
1 __NSArrayI Retain 00:16.513.595 2 0x660bb40 0 InfantCare -[Supplemental_Amount setFieldLabels:]
2 __NSArrayI Release 00:16.513.595 1 0x660bb40 0 InfantCare -[Supplemental_Amount viewDidLoad]
然后我更改了代码,而不是:
self.fieldLabels = array;
我说:
[self setFieldLabels:array];
不再泄漏(据说!)。为什么会这样? 谢谢!
答案 0 :(得分:0)
两种语法都相同。鉴于您已使用retain属性声明了fieldLabels
属性,因此在调用setFieldLabels
(在您编写时调用:self.fieldLabels = array
)后,数组的引用计数为1是你所期望的。确实,鉴于代码中的调用顺序,会发生以下情况:
NSArray *array = [[NSArray alloc] initWithObjects:@"Amount (oz):", @"Amount (ml):", @"Supplement:", nil];
设置分配给1 self.fieldLabels = array;
将保留数组,释放fieldLabels
之前保留的内容并将fieldLabels
分配给保留的数组。在此阶段,数组的保留计数为2(来自init的1,来自属性赋值的1)。[array release];
将数组的保留计数恢复为1,这就是你想要的。