开发者

Why can I not release this NSString?

开发者 https://www.devze.com 2023-02-05 00:35 出处:网络
Here is the relevant开发者_运维技巧 code: NSString *address = [NSString stringWithFormat:@\"%@\", [defaultServer root]];

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 NSStrings 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号