views:

25

answers:

1

Hello - I am trying to create a game and have run into what is probably a pretty easy problem to solve.

As the player goes through the game, many objects (Vehicle) will be added and removed.

The Vehicles get added to an array called currentVehiclesMutableArray.

My problem is I cant figure out how to retain a Vehicle so that it remains in the array until I am finished with it.

+4  A: 

A NSMutableArray automatically retains anything you add to it.

In fact, you have to make sure you release an object after you added it, or you'll have a memory leak.

For example:

Vehicle *vehicle = [[Vehicle alloc] init];

[mutableArray addObject:vehicle];

[vehicle release]; // you should release it, because it was retained by the array

// at this point, mutableArray holds your vehicle object, and is retaining it
Philippe Leybaert
Okay thanks, This is what I am already doing but it is not working. It may just not be working for a different reason though. When i remove it from the array, is it released?
Brodie
In the [NSMutableArray reference](http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableArray) it says: "when you add an object to an array, the object receives a retain message. When an object is removed from a mutable array, it receives a release message"
progrmr