ios - 使用自定义对象从数组构建不可变的 NSDictionary,其中每个键可以有多个对象

标签 ios nsmutabledictionary

我试图查找此问题但没有成功,我想构建一个函数来创建键和对象的“不可变字典”,其中对象也是一个不可变数组。

我将传递给这个函数的是我创建的对象数组,每个对象都有一个键属性,我想用它来对字典中的对象进行分组。

我想出了这个,我测试了它并且它有效,但我想看看是否有更好/更安全的方法来做到这一点。

我确实使用 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/

相关文章:

ios - Xcode 测试版 6 iOS 8 : Simulator not working

ios - 这两段代码有什么区别?

ios - 更改嵌套 NSMutableDictionary 中的值

ios - 自动布局前导或尾随 -16

ios - apple watch通知后异步加载数据

iphone - keysSortedByValueUsingSelector 崩溃但 sortedArrayUsingSelector 运行正常

ios - nsdictionary 中的 block ?

objective-c - "Mutating method sent to immutable object"尽管对象是 NSMutableDictionary

iphone - 你的第二个 iOS 应用 : Edit one object in two different views

objective-c - 如何创建一个在分配 nil 时不会崩溃的 NSMutableDictionary?