NSSet setByAddingObjectsFromSet 保留计数
我以为我已经开始掌握 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您根本不必释放它。实际上,您绝对不能释放它。你不拥有它。这些保留来自 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.)