我试图查找此问题但没有成功,我想构建一个函数来创建键和对象的“不可变字典”,其中对象也是一个不可变数组。
我将传递给这个函数的是我创建的对象数组,每个对象都有一个键属性,我想用它来对字典中的对象进行分组。
我想出了这个,我测试了它并且它有效,但我想看看是否有更好/更安全的方法来做到这一点。
我确实使用 ARC,并且我想确保当我从函数返回时每件事都是不可变的。
- (NSDictionary* )testFunction:(NSArray *)arrayOfObjects
{
NSMutableDictionary *tmpMutableDic = [[NSMutableDictionary alloc] init];
for(MyCustomObject *obj in arrayOfObjects)
{
if ([tmpMutableDic objectForKey:obj.key] == nil)
{
// First time we get this key. add key/value paid where the value is immutable array
[tmpMutableDic setObject:[NSArray arrayWithObject:obj] forKey:obj.key];
}
else
{
// We got this key before so, build a Mutable array from the existing immutable array and add the object then, convert it to immutable and store it back in the dictionary.
NSMutableArray *tmpMutableArray = [NSMutableArray arrayWithArray:[tmpMutableDic objectForKey:obj.key]];
[tmpMutableArray addObject:obj];
[tmpMutableDic setObject:[tmpMutableArray copy] forKey:obj.key];
}
}
// Return an immutable version of the dictionary.
return [tmpMutableDic copy];
}
最佳答案
我认为这是大量的复制。我会等到最后才将可变数组转换为不可变数组,而不是每次要添加元素时都复制它:
- (NSDictionary *)testFunction:(NSArray *)arrayOfObjects
{
NSMutableDictionary *tmpMutableDic = [[NSMutableDictionary alloc] init];
for(MyCustomObject *obj in arrayOfObjects)
{
if ([tmpMutableDic objectForKey:obj.key] == nil)
{
// First time we got this key, add array
[tmpMutableDic setObject:[[NSMutableArray alloc] init] forKey:obj.key];
}
// Add the object
[[tmpMutableDic objectForKey:obj.key] addObject:obj];
}
// Convert mutable arrays to immutable
for (NSString *key in tmpMutableDic.allkeys) {
[tmpMutableDic setObject:[[tmpMutableDic objectForKey:key] copy] forKey:key];
}
// Return an immutable version of the dictionary.
return [tmpMutableDic copy];
}
关于ios - 使用自定义对象从数组构建不可变的 NSDictionary,其中每个键可以有多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389531/