Replace a value in NSDictionary in iPhone

前端 未结 5 1356
悲哀的现实
悲哀的现实 2020-12-08 00:31

I have a array (dataArray) of NSDictionary \"item\". It has datas like \"david\" for key \"name\" and \"85\" for key \"marks\" etc for 5 students. I want to replace the mark

相关标签:
5条回答
  • 2020-12-08 01:13

    You first need an NSMutableDictionary with it you can change the key and value.

    It would be like this:

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"david", @"name", "85", @"marks", nil];
    
    [dict setObject:@"90" forKey:@"david"];
    
    0 讨论(0)
  • 2020-12-08 01:15
     // NSDictionary *dict = ...
        NSMutableDictionary *mutableDict = [dict mutableCopy];
        [mutableDict setObject:@"myObject" forKey:@"myKey"];
        dict = [mutableDict mutableCopy];
    

    I hope it helps

    0 讨论(0)
  • 2020-12-08 01:18

    If you want to update an object in a NSDictionary you should use NSMutableDictionary instead. NSMutableDictionary has the following EXTRA methods

    Adding Entries

    • setObject:forKey:
    • setValue:forKey:
    • addEntriesFromDictionary:
    • setDictionary:

    Removing Entries

    • removeObjectForKey:
    • removeAllObjects
    • removeObjectsForKeys:
    0 讨论(0)
  • 2020-12-08 01:30

    Here's what you can do:

    NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
    NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
    [newDict addEntriesFromDictionary:oldDict];
    [newDict setObject:@"Don" forKey:@"Name"];
    [dataArray replaceObjectAtIndex:0 withObject:newDict];
    [newDict release];
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-08 01:32
    [davidsRecord setObject:@"100" forkey:@"mark"];
    
    0 讨论(0)
提交回复
热议问题