Why can I not release this NSString?
Here is the relevant开发者_运维技巧 code:
NSString *address = [NSString stringWithFormat:@"%@", [defaultServer root]];
address = [address stringByAppendingFormat:@"%@", [defaultServer login]];
address = [address stringByAppendingFormat:@"?%@", [params urlEncodedString]];
NSString *response = [[NSString alloc] init];
response = [self getResponseFromWebAddress:address];
[response release];
[address release];
This code does not error here, but later inside of some Apple Libraries it throws a "message sent to deallocated instance" error. However, if I comment out the line [address release]
it works fine. Why? I don't quite understand memory management and this one confuses me.
This line:
NSString *address = [NSString stringWithFormat:@"%@", [defaultServer root]];
And its following lines all work with autoreleased NSString
s supplied by the stringWithFormat:
and stringByAppendingFormat:
methods. You're not supposed to release address
manually, since the autorelease pool will handle that for you.
And here:
NSString *response = [[NSString alloc] init];
response = [self getResponseFromWebAddress:address];
You are allocating a new NSString
, then immediately pointing the response
variable to another string which is autoreleased ([self getResponseFromWebAddress:address]
). The allocated object no longer has any available pointers, so you can't release it anymore, and therefore it leaks.
To fix both issues, remove the alloc-init line and the release lines. Your address
string can also be initialized with just one statement:
// Combine all three arguments into one format string
NSString *address = [NSString stringWithFormat:@"%@%@?%@",
[defaultServer root],
[defaultServer login],
[params urlEncodedString]];
NSString *response = [self getResponseFromWebAddress:address];
// No need to release either variable
Remember the NARC (new, alloc, retain, copy) rule. You have to release an object only if it was created by one of these messages. Otherwise the object will be autoreleased.
精彩评论