2

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.

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

4

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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.