简体   繁体   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]);

Why is the retain count 2 and not 1? 为什么保留计数为2而不是1?

Yes, You will get retain Count 2, one for alloc and other for stringWithFormat. 是的,您将获得保留Count 2,一个用于alloc,另一个用于stringWithFormat。 stringWithFormat is a factory class with autorelease but autorelease decreases retain count in the future. stringWithFormat是一个具有自动释放的工厂类,但autorelease会减少将来的保留计数。

You shoud not care about the absolute value of the retain count. 你不关心保留计数的绝对值。 It is meaningless. 这毫无意义。

Said that, let's see what happens with this particular case. 说,让我们看看这个特例会发生什么。 I slightly modified the code and used a temporary variable to hold the object returned by stringWithFormat to make it clearer: 我稍微修改了代码并使用临时变量来保存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.

You created a string and then used it to create another string. 您创建了一个字符串,然后使用它创建另一个字符串。 Instead, do this: 相反,这样做:

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

this is because you [[alloc] init] a first NSString so serverUrl have retain +1 and at the same line you call [NSString stringWithFormat] that return another nsstring on autorelease with retain count at 2 you should only use the : 这是因为你[[alloc] init]是第一个NSString,所以serverUrl保留+1并且你在同一行调用[NSString stringWithFormat],它在autorelease上返回另一个nsstring,保留计数为2,你应该只使用:

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

so your serverUrl will have retainCount to 1 and you don't have to release string 所以你的serverUrl将retainCount保留为1,你不必释放字符串

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

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