【问题标题】:NSSet setByAddingObjectsFromSet retain countNSSet setByAddingObjectsFromSet 保留计数
【发布时间】:2011-08-24 09:38:12
【问题描述】:

我以为我已经开始掌握 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?我必须释放它两次吗?我误会了什么?

非常感谢。

【问题讨论】:

标签: objective-c memory-management nsset


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多