I have a Mutable Dictionary that I removed an element from with removeObjectForKey. That’s fine, but when I enumerate thru the Dictionary, there is a ‘hole’ for the element I deleted. So when I print the Dictionary, it displays that element as (null).
Is there way to ‘pack’ the dictionary after removing an element? I need contiguous numbers for the keys. Example:
BEFORE DELETE:
key:1 value:red
key:2 value:green
key:3 value:blue
key:4 value:yellow
myDictionary removeObjectForKey:2
CURRENT:
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
Code to remove nil entry from NSMutableDictionary. This is what I came up with, but it is not working:
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;
}
That happens because the
NSDictionary(and its mutable subclass) acts like a hash/map/associative array. If you want to keep the indices running consecutively, you have to either reset them after removing an object, or just store everything in aNSMutableArray.