Delete all objects after index 20 in NSMutableDictionary?

I have an NSMutableDictionary that can contain more than twenty objects. If it contains more than 20 objects, how to delete old records, while there are 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 a maximum number of objects: 5, it should become:

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

Thank.

+3
source share
2 answers

If all you are looking for is 20 elements, I would 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;

, 20 , , . , , .

+1

NSNumbers , , , :

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

NSStrings, NSString .

, , , , - ( , NSMutableArray?)

+1

Source: https://habr.com/ru/post/1769826/


All Articles