Eric Brotto
Eric Brotto

Reputation: 54281

NSArray not iterating

I am trying to iterate through an NSArray with a for loop. The result only returns the last value in the array even though the int variable i is printing correctly (0,1,2...).

Also, if I set iteration to say 5, I will get the 6th object in the array, which is correct. I did this to try to narrow down the scope of possible causes.

Any ideas?

int i;
int j;
Buffer *vocalBuffer; 
for (i=0; i < numberOfBuffers; i++){ // loop through every vocal buffer

    Buffer *mixedBuffer = [[Buffer alloc] init];
    int array[sizeLoopBuff];
    mixedBuffer.buffer = array;
    mixedBuffer.numFrames = sizeLoopBuff;
    NSLog(@"Vocal buffer number --> %i", i);
    NSInteger iteration = i;
    vocalBuffer = [arrayOfVocalBuffers objectAtIndex:iteration]; // grab the vocal buffer

    for (j=0; j < sizeLoopBuff; j++){ // run through a beat loop cycle.
        mixedBuffer.buffer[j] = loopBuffer.buffer[j]; // add the beats to return buffer.
        if (j > insertPoint && j < insertPoint+ vocalBuffer.numFrames){
            mixedBuffer.buffer[j] = loopBuffer.buffer[j] + vocalBuffer.buffer[j-insertPoint];
        }
    }
    [mutArray addObject:mixedBuffer];
}

Upvotes: 0

Views: 112

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31026

As figured out in the comments, the use of a pointer to stack storage has some problems. One is that while it's in scope, its content is overwritten by each use within a loop; individual objects with pointers to it do not have unique copies.

The other problem is that once the method returns and its stack space isn't needed (as far as the runtime is concerned), there's no predicting what will be done with the space.

The necessary behavior of having a unique buffer per object suggests that the object should allocate its own buffer dynamically when created.

Upvotes: 2

Related Questions