Creating and using an Array of objects in Objective-C

Saturday, April 4, 2009

First we need an array to hold the objects (in this case bullets)

1NSMutableArray *myBullets = [[NSMutableArray alloc] init]; Create and then add the objects for (int i=0; i<5; i++){ //create Bullet *newBullet = [[Bullet alloc] init]; //add to the array [myBullets addObject: newBullet]; //release the object here as its retained in the array [newBullet release]; }``` `myBullets` now has 5 bullets in it. Then to modify the object: ```objectivec // Retrive an item theBullet = [myBullets objectAtIndex:i]; //do stuff or modify theBullet theBullet.position.x += 1; 

To remove an object from the array use:

1//removes the 3rd item //remember an array starts at 0! [myBullets removeObjectAtIndex:2]; 

Other posts

Tagged with: