2011-05-12 48 views
0

我以爲我開始在內存管理掛在objective-c,但我有點困惑我從增加集合中獲得的保留計數。對於setByAddingObjectsFromSet的阿比說:NSSet setByAddingObjectsFromSet保留計數

Returns a new set formed by adding the objects in a given set to the receiving set. 

- (NSSet *)setByAddingObjectsFromSet:(NSSet *)other 

所以我有點這個疑惑:

NSSet* tom = [[NSMutableSet alloc] initWithCapacity:1]; 
NSSet* dick = [[NSMutableSet alloc] initWithCapacity:1]; 
NSSet* harry = [tom setByAddingObjectsFromSet:dick]; 

printf("tom retainCount: %d \n", [tom retainCount]); 
printf("dick retainCount: %d \n", [dick retainCount]); 
printf("harry retainCount: %d \n", [harry retainCount]); 

主要生產:

tom retainCount: 1 
dick retainCount: 1 
harry retainCount: 2 

如果setByAddingObjectsFromSet返回一組新的,爲什麼是retainCount 2?我必須兩次釋放它嗎?!我誤解了什麼?

非常感謝。

+4

不要使用retainCount:http://stackoverflow.com/questions/5784084/calling-retaincount-considered-harmful – 2011-05-12 19:15:22

+1

另請參閱:[1 ](http://stackoverflow.com/questions/5155559/weird-behaviour-with-retaincount)[2](http://stackoverflow.com/questions/5233143/retaincount-in-blocks-show-extrange-behavior) [3](http://stackoverflow.com/questions/5483357/nsstring-retaincount-is-2147483647)[4](http://stackoverflow.com/questions/5391479/why-is-the-retaincount-still- 1-after-object-release)[5](http://stackoverflow.com/questions/3354724/dont-worry-about-retaincount-really)[6](http://stackoverflow.com/questions/5220902/ )[...](http://stackoverflow.com/search?page=3&tab=relevance&q=retaincount) – 2011-05-12 19:18:58

回答

2

你根本不需要釋放它。其實,你一定不能發佈它。你不擁有它。這些保留來自Cocoa,Cocoa負責照顧它 - 他們不是你關心的問題。 (這是爲什麼看retainCount是不可取的原因之一。)