从NSDictionary中删除Key为空字符串的值

时间:2018-04-13 09:57:02

标签: ios objective-c json uitableview nsdictionary

我正在收到这样的JSON响应:

{
    "partner_wise": {
        “partner1”: {
            "processing": 254,
            "complete": 0,
            "track_invoice": 0,
            "bar_code": 0
       },
        "": {
            "processing": 0,
            "complete": 0,
            "track_invoice": 0,
            "bar_code": 0
             },
        “partner2”: {
            "processing": 0,
            "complete": 0,
            "track_invoice": 0,
            "bar_code": 0
        }
      }
}

我在tableView中以索引方式设置这些值。从这个JSON响应中,我没有必要显示哪个键是空字符串的值。如何从NSDictionary中删除此对象。

3 个答案:

答案 0 :(得分:2)

您无法从NSDictionary中删除这些对象。 NSDictionary是一个不可变的对象 但是你可以制作一个可变副本并删除不需要的密钥:

10.3

答案 1 :(得分:1)

您可以使用removeObjectForKey

[dictionary removeObjectForKey:@""];

示例代码:

//your json dictionary here!
NSDictionary *finalDictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"11111111",@"",@"00000000",@"testkey1", nil];

NSMutableDictionary *dictionaryColection = [[NSMutableDictionary alloc] initWithDictionary:finalDictionary];
NSLog(@"Dictionary Full: %@", dictionaryColection);

[dictionaryColection removeObjectForKey:@""];
finalDictionary = dictionaryColection;
NSLog(@"Final dictionary removed: %@", finalDictionary);

日志:

Dictionary Full: {
    "" = 11111111;
    testkey1 = 00000000;
}

Final dictionary removed: {
    testkey1 = 00000000;
}

答案 2 :(得分:-2)

在swift 3.0中

dictionary.removeObject(forKey: "")