开发者

Need a memory management clarification wrt NSArray

Say I have:

NSDictionary *stuff; // {"1" => "hi", "2" => "bye"}
NSArray *array = [stuff allKe开发者_开发技巧ys];

allKeys makes a copy of stuff's keys, so array is now responsible for releasing this information.

Later on, when I want to

I cannot do:

array = [newStuff allKeys];

because it would just reassign the pointers and orphan the original array. I must first remove the objects

[array removeAllObjects];

Wanted to know if my understand is correct? Thanks!


Not quite.

NSArray *array = [stuff allKeys];

This gives you an array that you don't own. Whether it's technically a copy or not is not your problem. Since the accessor doesn't start with the word "alloc" or "new", or contain the word "copy", you don't own the return value, which means you don't need to release it. (But you do need to retain it if you want to keep it.)

If you later do this:

array = [newStuff allKeys];

that's fine. It stomps on the original reference, as you know, but since you don't own that reference anyways, it's OK to let it go. This new reference is also, of course, not yours unless you retain it.


No. allKeys returns an autoreleased NSArray. It will be released later unless you explicitly retain it. So setting array = [newStuff allKeys]; is perfectly fine. You should probably read this guide on Objective-C.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜