我正在研究iphone应用程序,虽然我认为我对内存管理有很好的理解,但在使用Xcode Analyze功能后我发现了一些问题。我已经看过很多我在这里可以找到的问题了,但我找不到与我的情况类似的问题。
CustomerDetailController.h
@interface CustomerDetailController : UITableViewController {
PTCustomer *customer;
}
@property (nonatomic, retain) PTCustomer *customer;
- (id)initWithCustomer:(PTCustomer *)aCustomer;
CustomerDetailController.m
@synthesize customer;
- (id)initWithCustomer:(PTCustomer *)aCustomer {
if ((self = [super initWithStyle:UITableViewStyleGrouped]))
{
if (aCustomer != nil)
self.customer = aCustomer;
else
self.customer = [[PTCustomer alloc] init]; // This line shows Potential leak of an object allocated on line ##
}
return self;
}
如果我点击分析器标记的项目,则说:
Method返回一个具有+1保留计数的Objective-C对象
对象泄露:此执行路径中未引用已分配的对象,并且保留计数为+1
我的理由是,如果未传入PTCustomer对象,我想初始化一个新对象,以便我可以在此类别的其他地方使用它。
这样做的正确方法是什么?
感谢。
答案 0 :(得分:3)
self.customer
被过度保留
客户分配+1
属性设置者保留客户时+1。
不保留customer
,属性设置者将保留它。
只需:
self.customer = [[[PTCustomer alloc] init] autorelease];
但鉴于这是一种init方法,有一个强有力的论据,即应该直接指定ivar:
customer = [[PTCustomer alloc] init];
答案 1 :(得分:1)
另一个选项是将保留的对象直接分配给customer
而不是self.customer
。这绕过了setCustomer
方法中的自动保留逻辑。但是,如果这样做,则必须确保释放customer
引用的任何先前对象(例如,通过将nil分配给self.customer
)。
(因为以这种方式绕过setter是一种有点不规则的技术,有些人会对它皱眉。)
答案 2 :(得分:0)
您是否在dealloc中发布了customer
ivar?如果没有,那就是你的泄漏。