addObject replaces previous object in NSMutableArray

前端 未结 2 1513
眼角桃花
眼角桃花 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);
    
    }
    

提交回复
热议问题