2011-05-12 46 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是不可取的原因之一。)