0

我以为我开始掌握objective-c中的内存管理,但我对将集合加在一起得到的保留计数有点困惑。setByAddingObjectsFromSet 的 api 说:

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

1 回答 1

2

您根本不必释放它。实际上,你不能释放它。你不拥有它。那些保留物来自 Cocoa,照顾它是 Cocoa 的责任——它们不是你关心的。(这是不建议查看的众多原因之一retainCount。)

于 2011-05-12T19:21:14.247 回答