删除 NSMutableDictionary 中索引 20 之后的所有对象?
我有一个 NSMutableDictionary,可能包含二十多个对象。 如果它包含超过 20 个对象,我应该如何删除最旧的条目,直到只剩下 20 个?
例如,带有对象的 NSMutableDictionary:
a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;
f = "-1253254618";
g = 1401181143;
h = "-239350392";
i = "-1879881927";
最大对象数: 5,应该变为:
a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您要查找的只是 20 个元素,我会尝试以下操作:
想法是将找到的前 20 个键的元素复制到新字典中,然后用新字典替换旧字典。如果您想通过其他方式迭代字典,您也可以这样做,但上面的代码不必做太多改变。
If all you're looking for is 20 elements, I'd try something like:
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.
如果键是 NSNumbers 并且您知道它们是连续的,并且您想要删除较低的值,那么:
如果您的键是 NSString,则只需创建具有相应格式的 NSString 即可。
如果您的键不是连续的,那么您必须有一个并行字典,其中包含每个条目的存储日期,这样您就知道每个条目的存储时间并且可以删除最旧的条目,或者您需要完全使用其他内容(如果您将连续整数存储为键,那么使用 NSMutableArray 不是更容易吗?)
If the keys are NSNumbers and you know they're sequential, and you want to remove the lower values, then:
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?)