簡體   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