views:

72

answers:

2

Hi!

I have an NSMutableDictionary that possibly contains more than twenty objects. If it contains more than 20 objects, how should I remove the oldest entries until there is only 20 left?

For example, NSMutableDictionary with objects:

a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;
f = "-1253254618";
g = 1401181143;
h = "-239350392";
i = "-1879881927";

With max number of objects: 5, should become:

a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;

Thank you.

+1  A: 

If the keys are NSNumbers and you know they're sequential, and you want to remove the lower values, then:

int limit=20; //set to whatever you want
int excess = limit - [dict count];
if (excess > 0) {
  for (int i = 1; i <= excess; i++) {
    [dict removeObjectForKey:[NSNumber numberWithInt:i]];
  }
}

If your keys are NSStrings then just create the NSString with the corresponding format.

If your keys are not sequential, then you would have to either have a parallel dictionary with the date of storage for each entry, so you would know when each entry was stored and you can remove the oldest, or you need to use something else entirely (if you are storing sequential integers as keys, wouldn't it be easier to use NSMutableArray?)

Chochos
The initial question was a bit misleading, it does not contain numbers at all. It contains NSStrings.
Emil
then just replace the NSNumber with [NSString stringWithFormat:"%d", i]
Chochos
+1  A: 

If all you're looking for is 20 elements, I'd try something like:

NSMutableDictionary* newDict = [NSMutableDictionary new];
int                  count = 0;

for (id theKey in oldDict)
{
    [newDict setObject:[oldDict getObjectForKey:theKey] forKey:theKey];

    if (++count == 20)
        break;
}

[oldDict release];
oldDict = newDict;

The idea being that you copy the elements of the first 20 keys you find into a new dictionary, then replace the old one with the new one. If you want to iterate the dictionary via other means you could do that too, but the code above wouldn't have to change much.

fbrereto
Seems like a good idea, I will try that.
Emil
What does `++count` do, by the way?
Emil
it increments `count` by 1 before reference to `count`, btw `count++` increments `count` after reference
NR4TR