Basic Question about iPhone Object C Arrays and Deep and Pointer Copy
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 ...
addObject:
does a shallow copy. What you're missing is that NSMutableArray
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.
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.
NSString *foo = [[NSString alloc] initWithString@"bar"]; // retain count +1
[anArray addObject:foo]; // NOT COPIED, but retain count of 'foo' increased by 1
[foo release]; // retain count of foo decreased 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.
// some time later..
[anArray release]; // anArray released, foo retain count = 0.. foo gets released.
Kind Regards, Christian
精彩评论