我使用CFPropertyListCreateDeepCopy
制作NSDictionary
的深层可变副本。这个例子工作正常。
NSDictionary *test = @{@"1": @"One"};
NSMutableDictionary *dictionary = (__bridge NSMutableDictionary *)CFPropertyListCreateDeepCopy(NULL, (__bridge CFDictionaryRef)test, kCFPropertyListMutableContainersAndLeaves);
当NSDictionary
使用NSNumber
作为键值时,这不起作用。 CFPropertyListCreateDeepCopy
返回nil
。这是一个例子。
NSDictionary *test = @{@(1): @"One"};
NSMutableDictionary *dictionary = (__bridge NSMutableDictionary *)CFPropertyListCreateDeepCopy(NULL, (__bridge CFDictionaryRef)test, kCFPropertyListMutableContainersAndLeaves);
如何制作以NSDictionary
为关键值的NSNumber
的深层副本?
答案 0 :(得分:1)
虽然NSDictionary和CFDictionary对象允许它们的键是任何类型的对象,但如果键不是字符串对象,则集合不是属性列表对象。
您无法使用非字符串键复制属性列表,因为这不是属性列表。
只需遍历字典并手动复制项目。
Owner
对@implemenatation NSDictionary (DeepCopy)
- (NSMutableDictionary*)deepMutableCopy
{
NSMutableDictionary *copy = [NSMutableDictionary new];
[self enumerateKeysAndObjectsUsingBlock
^(id key, id object)
{
if([object respondsToSelector:@selector(deepMutableCopy)])
{
object = [object deepMutableCopy];
}
else if ([object respondsToSelector:@selector(mutableCopy)])
{
object = [object mutableCopy];
}
else if ([object respondsToSelector:@selector(copy)]) // Maybe, maybe not
{
object = [object copy];
}
[copy setObject:object forKey:key]
}];
return copy;
}
执行相同操作。
(对于此类任务,我希望在Objective-C中包含组件。)