How do I add object to NSMutableDictionary with key?
Solution 1
I think you should create array of dictionary. Just add your finalBooks dictionary to NSMutableArray like this
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];
}
}
And you will get array of dictionary. Good Luck !!
Solution 2
setValue method in a NSMutableDictionary replaces the value if the key is same. So what you can do is either use NSMutableDictionary of arrays or dictionaries.
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];
}
}
If you want everything in one dictionary, I suggest you use a unique key such as NSString stringWithFormat:@"ID+%@",username],...[NSString stringWithFormat:@"username+%@",username]
But it looks messy :)
Admin
Updated on December 28, 2020Comments
-
Admin over 3 years
I have a plist. I want add the elememts from that plist to a mutable dictionary. First I check the user name in the plist, and my current name are same or not. If it is same, then I want to add all value to that dictionary rom plist, and also assign the same key:
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] this value is 7 so each value replacing 6 times ,and am getting only final values I want every values matching to user name I that mutabledictionary.
-
Arcank almost 9 yearsShouldn't you use -objectForKey:/-setObject:forKey:?