Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
997 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...