本文介绍了我们如何限制NSMutableDictionary的容量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法创建容量为 limit 而不是初始容量的可变字典?

Is there any way to create a mutable dictionary with a capacity limit rather than an initial capacity?

说要创建一个最多只能有100个条目的字典。

Say you want to create a dictionary that will only ever have, at most, 100 entries.

字典的容量参数是初始容量,如果您添加的元素多于您的话,其容量将简单地增加

The capacity argument for the dictionary is an initial capacity that will be simply increased if you add more elements than you want so it's not suitable.

推荐答案

子类化并覆盖addObject以在添加之前检查计数吗?没有内置方法。

Subclass it and override addObject to check count before adding? No built-in way.

这是一个基本示例,未经测试,缺少init等,但这是核心。您还应该以类似的方式重写setValue:forKey:。

Here is a basic example... not tested, missing init etc, but this is the core. You should also override setValue:forKey: in a similar manner.

@interface MyMutableDictionary: NSMutableDictionary

- (BOOL) setObject:(id)anObject forKey:(id)aKey;

@end

@implementation MyMutableDictionary

- (BOOL) setObject:(id)anObject forKey:(id)key {
    if ([self count] < yourLimit) {
        [super setObject:anObject forKey:key];
        return YES;
    }
    return NO;
}

@end

这篇关于我们如何限制NSMutableDictionary的容量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 13:17