我正在尝试创建 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/