How do I fix a leaked object with a retain count of +1?

110 Views Asked by At

I have a leaked object in the following code. How do I fix it? I tried adding a [apiViewController release]; but when I analyze the app I still get a :

enter image description here

 if (idx == 2) {
        NSLog(@"you touched menu 2");

        APICallsViewController *apiViewController = [APICallsViewController alloc];
        [self.navigationController pushViewController:apiViewController animated:YES]; 
        //[apiViewController getFriendsCallAPIDialogFeed];
        [apiViewController getAppUsersFriendsUsing];


    }

thanks for any help

3

There are 3 best solutions below

0
On BEST ANSWER

You are forgetting the -init, and the -release.

APICallsViewController *apiViewController = [[APICallsViewController alloc] init];
...
[apiViewController release];

You probably need to read up on Objective-C programming.

0
On

For every object you alloc/retain, you are responcible for releasing.

After

[apiViewController getAppUsersFriendsUsing];

Put...

[apiViewController release];
0
On

First, you need the init, as hwaxxer and Justin Boo suggest.

Second, several people have suggested using autorelease. The autorelease is a deferred release, and you generally should not do so unless you need to (e.g. your method needs to defer the release until later so that it can return the object to its caller). So, in short, only use autorelease when you're returning the object to the method's caller, and otherwise use release. In this case, you should use release.

In this particular scenario, it doesn't matter (because by pushing the view controller, it's getting retained anyway and won't be released until that view is popped off the stack), but if you're going to do your own memory management (i.e. not use ARC), it's worthwhile employing good practice, namely, release whenever you can (such as in this case) and only autorelease when you're returning object to the method's caller and therefore must defer the release.

Third, I'd suggest reading and making sure you understand Advanced Memory Management. This gives you some basic rules of memory management that you really need to understand (e.g., if you create it, then you own it, and you must release it).

Fourth, once you gain a proficiency in memory management (and only after you do, as it's useful to really understand what's going on), I'd suggest seriously considering Transitioning to ARC, because you don't have to deal with much of this silliness.