关于 iPhone 对象 C 数组以及深度和指针复制的基本问题
我是 iPhone / Mac 领域的新手,这可能是一个非常基本的问题,我做了一些搜索,但没有找到直接的答案。
我想知道数组/可变数组的 addObject 方法在添加时是否执行浅(仅指针)或深(复制对象)。
- 已分配的可变数组
- 已通过某种 init 分配的 NSString
- 我们将字符串添加到可变数组中
- 然后释放 NSString
如果这是正确的处理方式,则假定 addObject 会执行此操作NSString 的深层副本。只是确认这是使用可变数组进行内存管理的正确方法......
I am new to the iPhone / Mac space and this is probably a pretty basic question, I have done some searching and have not found the direct answer.
I would like to know if the addObject method for Arrays / Mutable Arrays does a shallow (pointer only) or deep (copies object) when adding.
- A mutable array that has been alloc
- A NSString that has been alloc with some sort of init
- We addObject the string to the mutable array
- We then release the NSString
If this is the proper way to do things, that it is assumed that the addObject will do a deep copy of the NSString. Just confirming that this is the proper way to do memory management with mutable array ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
addObject:
进行浅复制。您缺少的是 NSMutableArray 保留该对象,因此它不会消失,但不需要深层复制。这是 Objective-C 内存管理的一个关键点。您应该阅读内存管理编程指南 。 Cocoa 内存管理并不复杂,而且非常一致。我在三个魔词上有一个简短的摘要。addObject:
does a shallow copy. What you're missing is thatNSMutableArray
retains the object, so it does not go away, but does not require a deep copy. This is a key point to Objective-C memory management. You should read the Memory Management Programming Guide. Cocoa memory management is not complicated, and is incredibly consistent. I have a shortened summary at Three Magic Words.当将对象添加到数组时,其保留计数将会增加。当一个对象的保留计数为0时,它将被释放。因此,当将 NSString 添加到您的 anArray 时,它不会是一个副本(您可以更改 foo,它也会在数组中更改),但它会增加 foo 的保留计数1.
当你在某个时候释放一个Array时,它会对其对象调用release。所以foo的retain count最终会变成0并且foo会被释放。
亲切的问候,
基督教
When adding an Object to an Array, its retain count will be increased. A object will be released when its retain count is 0. So when adding the NSString to you anArray it won't be a copy (you can change foo and it will be changed in the array, too) but it will increase foo's retain count by 1.
When you at some time release anArray, it will call release on its objects. So foo's retain count will finally become 0 and foo will be released.
Kind Regards,
Christian