addObject替换NSMutableArray中的先前对象 [英] addObject replaces previous object in NSMutableArray
问题描述
我正在尝试通过for循环将对象添加到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.
推荐答案
您正在初始化for循环内的dataArray,因此每次重新创建它(意味着没有对象)并添加一个新对象
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
移动
dataArray = [[NSMutableArray alloc] init];
到for循环之前
当您用getResults数组中的对象立即覆盖postInfo
对象时,也无需分配/初始化postInfo
对象
also there is no need to alloc/init the postInfo
object when you immediately override it with the object from the getResults array
这篇关于addObject替换NSMutableArray中的先前对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!