views:

64

answers:

3

I am trying to clean up my code from memory leaks and I am having problems with the 'release' method.

Here is my code:

NSArray *dict = [[NSArray alloc] initWithContentsOfURL:url];

if (dict == nil) {
 UIAlertView *alert = [[UIAlertView alloc]
        initWithTitle:@"Error"
        message:@"Cannot retrieve content.  Please try again later."
        delegate:self
        cancelButtonTitle:@"OK"
        otherButtonTitles:nil];
 [alert show];
 [alert release];
 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
 return;
}
self.schedule = dict;
[dict release];
[url release]; //I receive a runtime error here, "BAD ACCESS"

I don't understand why when I don't get the same problem with the line above [dict release];

A: 

You are responsible for calling release eat time, you call either alloc, copy, or retain.

In this case you called alloc on dict, but (presumably, although it is not shown where url comes from) not on url.

Brad Smith
A: 

Since you didn't post the code showing how URL was created, here's a general rule to follow:

If create the object with a initializer that starts with "init", then you should probably release it. If it's created another way (convenience method), then it's autoreleased. For example:

NSArray *a = [[NSArray alloc]initWithContentsOfURL:url];   // release this later

NSArray *a = [NSArray arrayWithContentsOfURL:url];   // this will be auto released

Basically you just need to look at whether the framework gave you an autoreleased object or not, because you can't release an autoreleased object or you'll (obviously) get a crash.

Take a look at the Memory Management Guide. It should be required reading.

marcc
A: 

Objective-C allows you to send messages (e.g. 'release') to nil pointers without consequence.

If the pointer is non-nil and points to something bogus (i.e. an object that's been released), you'll get an EXC_BAD_ACCESS exception. Where does the url parameter come from and what is its retain count ([url retainCount]) before you call release?

Chris Karcher