Creating and using an Array of objects

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

NSMutableArray *myBullets = [[NSMutableArray alloc] init];

Create and then add the objects

[code lang="c_mac"]
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.

To modify the object:

theBullet = [myBullets objectAtIndex:i];
//do stuff or modify theBullet
theBullet.position.x += 1; //add 1 to the x position

To remove an object from the array use:

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

Filled under

Discuss!

comments powered by Disqus