addObjectreplaceNSMutableArray中的前一个对象
我试图通过for循环将对象添加到NSMutableArray。 但似乎每当我添加一个对象,它会取代旧的,这样我只有一个对象在数组中…
你有什么想法可能是错的?
- (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); } }
这是RESULT TEST日志总是只显示输出中最后一个添加的string。
您正在初始化for循环内的dataArray,所以每次它都被创build(这意味着没有对象),并添加一个新的对象
移动
dataArray = [[NSMutableArray alloc] init];
到for循环之前
当你立即用getResults数组中的对象覆盖postInfo
对象时,也不需要分配/初始化postInfo
对象
你用这一行继续重新初始化数组:
dataArray = [[NSMutableArray alloc] init];
所以dataArray
被设置为一个新的(空)数组为循环的每一个运行。
而是在循环之前初始化数组。 尝试这样的事情:
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); }