addObject replaces previous object in NSMutableArray

人走茶凉 提交于 2019-12-14 03:57:16

问题


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.


回答1:


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




回答2:


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

}


来源:https://stackoverflow.com/questions/11808720/addobject-replaces-previous-object-in-nsmutablearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!