ios初始化函数内部的实例以在外部使用

时间:2011-09-12 19:13:30

标签: objective-c ios instance retain analyzer

xcode分析器告诉我一个方法返回一个带有+1保留计数的Objective-C对象: enter image description here

但是self.athletes是我在函数之外需要的一个对象......我怎么能解决这个'警告? 再次感谢

运动员的声明是这样的:

NSMutableArray *athletes;
@property (nonatomic, retain) IBOutlet NSMutableArray *athletes;

3 个答案:

答案 0 :(得分:2)

用这一行替换该行:

self.athletes = [NSMutableArray array];

我在这里写了完整的解释:Memory Management for properties with retain attribute

答案 1 :(得分:1)

由于您的属性定义为“retain”,因此使用点表示法将导致额外保留。 [[NSMutableArray alloc] init]的返回值保留为1,然后当您使用属性声明生成的setter函数设置属性时,它的保留计数为2.

要修复,请:

self.athletes = [NSMutableArray array]; // Returns an autoreleased object

或者,您也可以这样做:

athletes = [[NSMutableArray alloc] init]; // Doesn't use the setter generated by the property declaration, so doesn't retain again.

答案 2 :(得分:1)

有一种很好的方法可以解决这个问题(你在创建UI时已经使用过这种模式)。

NSMutableArray * athletesTemp = [[NSMutableArray alloc] init];

self.athletes = athletesTemp;

[运动员临时释放];

这里您不需要携带自动释放对象的负载。

相关问题