如何从NSMutableDictionary中删除nil条目

时间:2012-03-08 21:13:04

标签: objective-c nsmutabledictionary

我有一个Mutable Dictionary,我用removeObjectForKey删除了一个元素。这很好,但是当我通过字典枚举时,我删除的元素有一个“洞”。所以当我打印Dictionary时,它会将该元素显示为(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

DESIRED:

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;
}

1 个答案:

答案 0 :(得分:4)

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