hiwordls
hiwordls

Reputation: 781

IOS @property, @synthesize memory leak

I am developing an IOS application. I did analyze with XCode intruments, If I don't write autorelease then show "potential memory leak" message. Is that an error in the code block below. I was not sure.

//TransferList.h
@property (nonatomic,retain) WebServiceAPI *webApi;


//TransferList.m
@implementation TransferList

@synthesize webApi;

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webApi = [[[WebServiceAPI alloc] init] autorelease];
}

- (void)dealloc
{    

    [webApi release];
    [super dealloc];
}

Upvotes: 0

Views: 150

Answers (1)

Sulthan
Sulthan

Reputation: 130152

If this is compiled under MRC (and it obviously is), then without autorelease there will be a memory leak. That's absolutely correct.

alloc says you want the ownership of the object
Assigning to the property which is retain also claims ownership (by the property)
In dealloc you are releasing the property (the property won't own the object any more).

If there is no autorelease, viewDidLoad will never lose ownership of the object and you will have a memory leak because the object won't ever be deallocated.

- (void)viewDidLoad {
    [super viewDidLoad];

    //create the object and get the ownership
    WebServiceAPI *api = [[WebServiceAPI alloc] init];

    //let our property also own this object
    self.webApi = api;

    // I don't want to own the object anymore in this method
    // (of course, using autorelease is simpler)
    [api release];
}

- (void)dealloc {    
    //our property doesn't want to own the object any more
    [webApi release];
    [super dealloc];
}

Upvotes: 3

Related Questions