iosobjective-cnsdictionarynsmutabledictionary

How do I add object to NSMutableDictionary with key?


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.


Solution

  • 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 !!