addObject replaces previous object in NSMutableArray

前端 未结 2 1402
眼角桃花
眼角桃花 2020-12-21 17:57

I\'m trying to add objects to a NSMutableArray through a for loop. But it seems whenever I add an object it replaces the old one so that I only have one object in the array

相关标签:
2条回答
  • 2020-12-21 18:36

    You keep re-initializing the array for every run of the loop with this line:

    dataArray = [[NSMutableArray alloc] init];
    

    So dataArray is set to a new (empty) array for every run of the loop.

    Initialize the array before the loop instead. Try something like this:

    dataArray = [[NSMutableArray alloc] init];
    
    for (NSInteger i = 0; i < [getResults count]; i++) {
    
        PostInfo *postInfo = [getResults objectAtIndex:i];
    
        [dataArray addObject:postInfo.noteText];
    
        NSLog(@"RESULT TEST %@", dataArray);
    
    }
    
    0 讨论(0)
  • 2020-12-21 18:47

    you are initialising the dataArray inside the for loop, so everytime it is created again (which means there are no objects) and a new object is added

    move

    dataArray = [[NSMutableArray alloc] init];
    

    to before the for loop

    also there is no need to alloc/init the postInfo object when you immediately override it with the object from the getResults array

    0 讨论(0)
提交回复
热议问题