NSSet setByAddingObjectsFromSet 保留计数

发布于 2024-11-07 09:05:28 字数 832 浏览 0 评论 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 返回一个新集合,为什么保留计数为 2?我必须释放两次吗?我误解了什么?

多谢。

I thought I was starting to the hang of memory management in objective-c but I'm a little confused by the retain count I'm getting from adding sets together. The api for setByAddingObjectsFromSet says:

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

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

So I'm a bit puzzled by this:

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]);

Which produces:

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

If setByAddingObjectsFromSet returns a new set why is the retainCount 2? Do I have to release it twice?! What have I misunderstood?

Thanks alot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

机场等船 2024-11-14 09:05:28

您根本不必释放它。实际上,您绝对不能释放它。你不拥有它。这些保留来自 Cocoa,Cocoa 负责处理它们——它们与您无关。 (这是不建议查看 retainCount 的众多原因之一。)

You don't have to release it at all. Actually, you must not release it. You don't own it. Those retains are from Cocoa, and it's Cocoa's responsibility to take care of it — they're not your concern. (This is one of the many reasons why looking at retainCount is inadvisable.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文