Objective c 如何从NSMutableDictionary中删除nil项

Objective c 如何从NSMutableDictionary中删除nil项,objective-c,nsmutabledictionary,Objective C,Nsmutabledictionary,我有一个可变字典,我用removeObjectForKey从中删除了一个元素。这很好,但是当我通过字典枚举时,我删除的元素有一个“洞”。因此,当我打印字典时,它将该元素显示为null 是否有方法在删除元素后“打包”词典?我需要钥匙的连续号码。例如: 删除前: key:1 value:red key:2 value:green key:3 value:blue key:4 value:yellow myDictionary removeObjectForKey:2 当前: key:1 valu

我有一个可变字典,我用removeObjectForKey从中删除了一个元素。这很好,但是当我通过字典枚举时,我删除的元素有一个“洞”。因此,当我打印字典时,它将该元素显示为null

是否有方法在删除元素后“打包”词典?我需要钥匙的连续号码。例如:

删除前:

key:1 value:red
key:2 value:green
key:3 value:blue
key:4 value:yellow

myDictionary removeObjectForKey:2
当前:

key:1 value:red
key:3 value:blue
key:4 value:yellow
期望的:

key:1 value:red
key:**2** value:blue
key:**3** value:yellow
用于从NSMutableDictionary中删除nil项的代码。这是我想到的,但它不起作用:

int count = dictFaves.count;
int x = 1;  // Dictionaries are 1-relative
while ( x <= count ) {

   // get the current row
   NSString *curRow = [NSString stringWithFormat:@"%d", x];
   NSString *temp = [dictFaves objectForKey:curRow];

   // is this row empty? if so, we have found our hole to plug
   if ( temp == nil ) {
       // copy the Fave from the 'next' row to the 'current' row. Effectively   
       //   shifting it 1 lower in the Dictionary
       NSString *nextRow = [NSString stringWithFormat:@"%d", x + 1];
       temp = [dictFaves objectForKey:nextRow];
       [dictFaves setObject:temp forKey:[NSNumber numberWithInt:x]];

       // one final thing to cleanup: remove the old 'next' row. 
       // It has been moved up 1 slot (along with all others)
       [dictFaves removeObjectForKey:[NSString stringWithFormat:@"%d", x+1]];
   }
   x = x + 1;
}

这是因为NSDictionary及其可变子类的行为类似于散列/映射/关联数组。如果要保持索引连续运行,则必须在删除对象后重置索引,或者将所有内容存储在NSMutableArray中。

恐怕我的设计太过火,无法更改为NSMutableArray。糟糕的计划。我不需要索引连续运行-如果我可以删除字典中通过删除条目而创建的漏洞,我会很高兴。我在上面添加了代码来做这件事,但它不起作用…@巴斯曼:你在说什么洞?我认为hole是一种表示数字不连续的方式。如果你不想使用可变数组,那么你必须遍历字典并手动设置键以满足你的要求。@Chuck:是的,一旦我删除一个条目,数字就不再连续。@Alexander:我接受了你的建议。像冠军一样工作。现在唯一的问题是UITableView在删除空条目之前会重新加载。当它命中该条目时,它将中止。我刚刚发布了另一个问题。谢谢你的帮助。