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 at the time…
Do you have any idea of what might be wrong?
- (void)viewDidLoad
{
[super viewDidLoad];
LoginInfo *info = [[LoginInfo alloc] init];
info.startPost = @"0";
info.numberOfPosts = @"10";
info.postType = @"1";
getResults = [backendService getAllPosts:info];
for (NSInteger i = 0; i < [getResults count]; i++) {
Post *postInfo = [[Post alloc] init];
postInfo = [getResults objectAtIndex:i];
dataArray = [[NSMutableArray alloc] init];
[dataArray addObject:postInfo.noteText];
NSLog(@"RESULT TEST %@", dataArray);
}
}
It’s the RESULT TEST log that always shows only the last added string in the output.
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
to before the for loop
also there is no need to alloc/init the
postInfoobject when you immediately override it with the object from the getResults array