向数组添加对象,数组返回null

Adding objects to array, array returning null

我有 2 个从数据库接收信息的数组。一个名为 json,包含带有用户 ID 的帖子,另一个名为 userJson,包含所有用户及其 ID。如果来自 json 的用户 ID 等于来自 userJson 的用户 ID,我想用该用户的用户名填充第三个数组。我正在使用以下代码:

NSDictionary *info = [json objectAtIndex:indexPath.row];
NSDictionary *userInfo = [userArray objectAtIndex:0];
for (int i=0; i<[json count]; i++) {
    if ([[userInfo objectForKey:@"user_id"] isEqualToString:[info objectForKey:@"user_id"]]) {
        [usernameArray addObject:[userInfo objectForKey:@"username"]];
    }
}

NSLog(@"%@", usernameArray);

usernameArray 是应该包含用户名的第三个数组。当我打印它时,它多次打印出 null。

您需要先添加:

usernameArray = [[NSMutableArray alloc]init];

然后将循环更改为以下内容:

NSDictionary *info = [json objectAtIndex:indexPath.row];
NSDictionary *userInfo;
for (int i=0; i<[userArray count]; i++) {
    userInfo = [userArray objectAtIndex:i];
    if ([[userInfo objectForKey:@"user_id"] isEqualToString:[info objectForKey:@"user_id"]]) {
        [usernameArray addObject:[userInfo objectForKey:@"username"]];
    }
}