为什么NSString保留计数2?

时间:2011-07-26 14:30:26

标签: iphone objective-c cocoa-touch nsstring

#define kTestingURL @"192.168.42.179"

...

NSString *serverUrl = [[NSString alloc] initWithString:
                        [NSString stringWithFormat:@"http://%@", kTestingURL]]; 
NSLog(@"retain count: %d",[serverUrl retainCount]);

为什么保留计数为2而不是1?

4 个答案:

答案 0 :(得分:5)

是的,您将获得保留Count 2,一个用于alloc,另一个用于stringWithFormat。 stringWithFormat是一个具有自动释放的工厂类,但autorelease会减少将来的保留计数。

答案 1 :(得分:5)

你不关心保留计数的绝对值。这没有意义。

说,让我们看看这个特例会发生什么。我稍微修改了代码,并使用临时变量来保存stringWithFormat返回的对象,以使其更清晰:

NSString *temp = [NSString stringWithFormat:@"http://%@", kTestingURL];
// stringWithFormat: returns an object you do not own, probably autoreleased
NSLog(@"%p retain count: %d", temp, [temp retainCount]);
// prints +1. Even if its autoreleased, its retain count won't be decreased
// until the autorelease pool is drained and when it reaches 0 it will be
// immediately deallocated so don't expect a retain count of 0 just because
// it's autoreleased.
NSString *serverUrl = [[NSString alloc] initWithString:temp];
// initWithString, as it turns out, returns a different object than the one
// that received the message, concretely it retains and returns its argument
// to exploit the fact that NSStrings are immutable.
NSLog(@"%p retain count: %d", serverUrl, [serverUrl retainCount]);
// prints +2. temp and serverUrl addresses are the same.

答案 2 :(得分:2)

您创建了一个字符串,然后用它来创建另一个字符串。相反,这样做:

NSString *SERVER_URL = [NSString stringWithFormat:@"http://%@", kTestingURL];

答案 3 :(得分:1)

这是因为你[[alloc] init]是第一个NSString,所以serverUrl保留了+1并且在同一行你调用[NSString stringWithFormat],它在autorelease上返回另一个nsstring,保留计数为2 你应该只使用:

  

NSString * serverUrl = [NSString stringWithFormat:@“http://%@”,kTestingURL];

所以你的serverUrl将retainCount保留为1而你不必释放字符串