views:

49

answers:

2

I'm new to objective-c and Im trying to write a little sample app that gets some XML from a remote server and outputs it to the console, but when I do it I get a EXC_BAD_ACCESS which I dont understand:

    NSString *FeedURL = @"MYURLGOESHERE";
    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:FeedURL]];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &err];
    NSString *theString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; 

    NSLog(@"Response: %@", theString);];

    [resp release];
    [err release];

When I comment out the [resp release] line I dont get it anymore, can someone please explain this to me :)

Thanks

+2  A: 
NSData *response = [NSURLConnection sendSynchronousRequest:…];

This is not an alloc/create/copy method so you should not release response.

NSString *theString = [[NSString alloc] initWithData:…];

But you should release theString.

KennyTM
did you know that because of the same reason Michael said, which was that the method name did not mention alloc or copy?
Mark
@Mark: Yes. See http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmRules.html for detail.
KennyTM
One small addendum; another Cocoa convention is for class factory methods beginning with the word 'new' (including the 'new' method itself) do not return auto-released objects and should also be released.
Luke Redpath
+2  A: 

You are releasing an object that you don't own; since "sendSynchronousRequest" contains neither the word "alloc" nor the word "copy" in its name, you know that any object it gives you will automatically be deallocated with "autorelease", and so what you have is, in effect, a double-delete.

Michael Aaron Safyan
Thanks Michael, thats something ill need to remember!
Mark
...or the word "new". Please take all advice on Cocoa memory management you get on SO with a grain of salt and read the Cocoa Memory Management Guide (http://developer.apple.com/mac/library/documentation/cocoa/conceptual/MemoryMgmt/MemoryMgmt.html)!
Barry Wark
@Barry, right, I didn't include an exhaustive list.
Michael Aaron Safyan