如何使用键将对象添加到NSMutableDictionary?

5 objective-c nsdictionary nsmutabledictionary ios

我有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"];


        }
    }
Run Code Online (Sandbox Code Playgroud)

[displayList count]这个值是7所以每个值替换6次,并且我只得到最终值 我希望每个值匹配到用户名i,即mutabledictionary

Aja*_*ary 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

你将获得一系列字典.祝好运 !!