Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

objective c - addObject replaces previous object in NSMutableArray

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...