开发者

What happens in cocoa touch when the objects that were added in an array are released?

I have the following code from Xcode (Cocoa touch):

//Here, the class Vector2 is a class I made that stores an x value and a y value (As with XNA).

Vector2 *pointOne = [[Vector2 alloc] initWithX:170 Y:224];
Vector2 *pointTwo = [[Vector2 开发者_如何学运维alloc] initWithX:193 Y:173];
Vector2 *pointThree = [[Vector2 alloc] initWithX:233 Y:67];
Vector2 *pointFour = [[Vector2 alloc] initWithX:276 Y:164];
Vector2 *pointFive = [[Vector2 alloc] initWithX:299 Y:226];
Vector2 *pointSix = [[Vector2 alloc] initWithX:276 Y:168];
Vector2 *pointSeven = [[Vector2 alloc] initWithX:193 Y:173];

//Add positions to array

NSArray * points = [[NSArray alloc] initWithObjects:pointOne, pointTwo, pointThree, pointFour, pointFive, pointSix, pointSeven, nil];

//release memory for Vector2's

[pointOne release];
[pointTwo release];
[pointThree release];
[pointFour release];
[pointFive release];
[pointSix release];
[pointSeven release];

My question is, will releasing the Vector2's make the array objects become empty as well?


NSArray retains its contents*. therefore, every Vector2 will be retained when added, and then either released when removed from the array or when the array is destroyed.

in the context of the OP, you could still use pointOne after you have called release on it (because the array holds a reference to the object), but it not advisable because whoever reads your program will read it twice and probably want to correct it. this is especially important because array semantics are as trivial as it gets. when dealing with another object, it may make a copy of the argument or do something else entirely.

you should either use pointOne before releasing the ivar, or access it from the array.

*by default. you could actually create an NSArray which does not retain its contents using CoreFoundation apis.


The vectors in the array are safe. This code looks fine, and correct.

The array retains the objects you give it so it has its own "ownership" of them. When the array is released, it releases all the objects that are inside it at that time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜