我有plist,我想从那个plist添加elememts到一个可变字典。首先我检查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次,并且只获得最终值我希望每个值与用户名i匹配,即mutabledictionary
答案 0 :(得分:12)
我认为你应该创建字典数组。只需将您的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];
}
}
你会得到一系列字典。祝你好运!!
答案 1 :(得分:3)
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]
但它看起来很乱:)