Search code examples
iphonecocoa-touchiosretaincount

Object leak using "retain"


I have a property defined with retain attribute which I am synthesizing:

@property (nonatomic, retain) UISwitch *mySwitch;

And inside my loadView I am doing this:

self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];

And finally inside my dealloc I am doing this:

self.mySwitch = nil;

Am I leaking this object (mySwitch) as I have used one alloc? Should I autorelease it while assigning it frame?

Please suggest.


Solution

  • The line:

    self.mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)];
    

    Actually calls retain twice- once for the alloc and again in the assignment to self.mySwitch (which is a property you've specified should retain any values assigned to it.) The fix I have been told is best is to add a call to autorelease on the line, making it:

    self.mySwitch = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, 20)] autorelease];