Jorge Vega Sánchez
Jorge Vega Sánchez

Reputation: 7590

Store instances of same class in a NSMutableArray

I'm creating a little game using Sprite-kit and i'm having problems trying to store an object which means an enemy in the game.I use the same strategy that i use in my C++ programs but with objective-C and pointers the strategy doesn't work.

enemigo *nemesis = [[enemigo alloc] init];
self.almacenEnemigos = [[NSMutableArray alloc] initWithCapacity:kNumEnemigos];

for(int i = 0; i < kNumEnemigos; i++)
{
    [nemesis pintarEnemigo:CGPointMake(20+5*i, 20+5*i)];
    [self.almacenEnemigos addObject:nemesis];
}

I want to create four enemies but at the end i only have four times the same memory address according to a unique enemy. The var almacenEnemigos is an class attribute in the SKScene class.

Upvotes: 0

Views: 92

Answers (1)

rdelmar
rdelmar

Reputation: 104082

You're only creating one instance of enemigo, there in your first line. You need to move the creation of the instances into the loop.

self.almacenEnemigos = [[NSMutableArray alloc] initWithCapacity:kNumEnemigos];

    for(int i = 0; i < kNumEnemigos; i++)
    {
        enemigo *nemesis = [[enemigo alloc] init];
        [nemesis pintarEnemigo:CGPointMake(20+5*i, 20+5*i)];
        [self.almacenEnemigos addObject:nemesis];
    }

Upvotes: 2

Related Questions