objective-c - NSMutableDictionary 的深层可变副本

标签 objective-c iphone

我正在尝试创建 NSMutableDictionary 的深拷贝并将其分配给另一个 NSMutableDictionary。字典包含一堆数组,每个数组都包含名称,键是一个字母(这些名称的第一个字母)。所以字典中的一个条目是'A' -> 'Adam','Apple'。这是我在一本书中看到的,但我不确定它是否有效:

- (NSMutableDictionary *) mutableDeepCopy
{
    NSMutableDictionary * ret = [[NSMutableDictionary alloc] initWithCapacity: [self count]];
    NSArray *keys = [self allKeys];

    for (id key in keys)
    {
        id oneValue = [self valueForKey:key]; // should return the array
        id oneCopy = nil;

        if ([oneValue respondsToSelector: @selector(mutableDeepCopy)])
        {
            oneCopy = [oneValue mutableDeepCopy];
        }
        if ([oneValue respondsToSelector:@selector(mutableCopy)])
        {
            oneCopy = [oneValue mutableCopy];
        }

        if (oneCopy == nil) // not sure if this is needed
        {   
            oneCopy = [oneValue copy];
        }
        [ret setValue:oneCopy forKey:key];

        //[oneCopy release];
    }
    return ret;
}
  • [onecopy release] 是否应该存在?
  • 我将如何调用此方法:

    self.namesForAlphabets = [self.allNames mutableDeepCopy];

这样可以吗?还是会导致泄漏? (假设我将 self.namesForAlphabets 声明为一个属性,并在 dealloc 中释放它)。

最佳答案

由于免费桥接,还可以使用CoreFoundation函数CFPropertyListCreateDeepCopy:

NSMutableDictionary *mutableCopy = (NSMutableDictionary *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)originalDictionary, kCFPropertyListMutableContainers);

关于objective-c - NSMutableDictionary 的深层可变副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1950361/

相关文章:

ios - 在 iOS 中将一个图像覆盖在另一个图像上

objective-c - 从 xib 到 Storyboard UIButton 还是没有?

ios - 通过 iphone xcode 中的应用程序处理来电

ios - UIDynamics 在 Swift 中不起作用

ios - 将数据传递给 UITableViewCell iOS

objective-c - Swift 数组与 C 的互操作性?

iphone - @iPhone : how to create twitter + OAuth custom login in our application

iphone - 如何处理 UIWebView 中的应用程序 URL?

ios - 使用 Segues 将 UINavigationViewController 切换到 UITabBarController

iphone - Objective-C 中的所有 +'s and -' 是什么意思?