繁体   English   中英

为什么NSString保留计数2?

[英]Why is NSString retain count 2?

#define kTestingURL @"192.168.42.179"

...

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

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

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

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

说,让我们看看这个特例会发生什么。 我稍微修改了代码并使用临时变量来保存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.

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM