Reputation: 47
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.
Upvotes: 1
Views: 1362
Reputation: 112855
self.customer
is 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:
self.customer = [[[PTCustomer alloc] init] autorelease];
But given that this is an init method there is a strong argument that the ivar should be assigned directly:
customer = [[PTCustomer alloc] init];
Upvotes: 2
Reputation: 47739
The other option is to assign the retained object directly to customer
rather than to self.customer
. This bypasses the auto-retain logic in the setCustomer
method. However, if you do that you must assure that any prior object referenced by customer
is released (eg, by assigning nil to self.customer
).
(Because bypassing the setter in this way is a somewhat irregular technique some folks frown on it.)
Upvotes: 1
Reputation: 9536
Are you releasing your customer
ivar in the dealloc? If not, there's your leak.
Upvotes: 0