I am working on an iphone application, and although I thought I had a good understanding of memory management, I’m seeing some issues after using the Xcode Analyze function. I have looked at many of the existing questions I could find on here, but I couldn’t find one that was similar to my situation.
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;
}
If I click on the item marked by the Analyzer, it then says:
-
Method returns an Objective-C object with a +1 retain count
-
Object leaked: allocated object is not referenced later in this execution path and has a retain count of +1
My reasoning behind this is that if a PTCustomer object was not passed in, I want to initialize a new one so that I have it available elsewhere within this class.
What is the correct way to do this?
Thanks.
self.customeris being over-retained.+1 for alloc of customer
+1 when the property setter retains customer.
Do not retain
customer, the property setter will retain it.Just:
But given that this is an init method there is a strong argument that the ivar should be assigned directly: