6

我有一个列表。我想将该 plist 中的元素添加到可变字典中。首先我检查plist中的用户名,我现在的名字是否相同。如果相同,那么我想将所有值添加到该字典 rom plist,并分配相同的键:

 for(int i=0;i<[displayList count];i++)
    {
        if([[[data valueForKey:@"username"] objectAtIndex:i] isEqualToString:user])
        {
            [finalBooks setValue:[[data valueForKey:@"ID"] objectAtIndex:i] forKey:@"ID"];
            [finalBooks setValue:[[data valueForKey:@"name"] objectAtIndex:i] forKey:@"name"];
            [finalBooks setValue:[[data valueForKey:@"Place"] objectAtIndex:i] forKey:@"Place"];
          [finalBooks setValue:[[data valueForKey:@"username"] objectAtIndex:i] forKey:@"username"];
            

        }
    }

[displayList count] 这个值是 7,所以每个值替换 6 次,并且只得到最终值我希望每个值都与用户名匹配,我那个可变字典。

4

2 回答 2

15

我认为你应该创建字典数组。只需像这样将您的 finalBooks 字典添加到 NSMutableArray

NSMutableArray *finalArray = [[NSMutableArray alloc]init];

(int i=0;i<[displayList count];i++)
{
    if([[[data valueForKey:@"username"] objectAtIndex:i] isEqualToString:user])
    {
        [finalBooks setValue:[[data valueForKey:@"ID"] objectAtIndex:i] forKey:@"ID"];
        [finalBooks setValue:[[data valueForKey:@"name"] objectAtIndex:i] forKey:@"name"];
        [finalBooks setValue:[[data valueForKey:@"Place"] objectAtIndex:i] forKey:@"Place"];
        [finalBooks setValue:[[data valueForKey:@"username"] objectAtIndex:i] forKey:@"username"];

        [finalArray addObject:finalBooks];
    }
}

你会得到字典数组。祝你好运 !!

于 2013-05-20T07:16:21.310 回答
3

如果键相同,则 NSMutableDictionary 中的 setValue 方法会替换值。所以你可以做的是使用数组或字典的 NSMutableDictionary。

NSMutableDictionary *userDictionary=[[NSMutableDictionary alloc]init];

(int i=0;i<[displayList count];i++)
{
    if([[[data valueForKey:@"username"] objectAtIndex:i] isEqualToString:user])
    {
        [finalBooks setValue:[[data valueForKey:@"ID"] objectAtIndex:i] forKey:@"ID"];
        [finalBooks setValue:[[data valueForKey:@"name"] objectAtIndex:i] forKey:@"name"];
        [finalBooks setValue:[[data valueForKey:@"Place"] objectAtIndex:i] forKey:@"Place"];
        [finalBooks setValue:[[data valueForKey:@"username"] objectAtIndex:i] forKey:@"username"];

        [userDictionary setObject:finalBooks forKey:user];
    }
}

如果您想要一本字典中的所有内容,我建议您使用唯一键,例如NSString stringWithFormat:@"ID+%@",username],...[NSString stringWithFormat:@"username+%@",username]

但它看起来很乱:)

于 2013-05-20T09:36:39.357 回答