CFPropertyListCreateDeepCopy不能将键作为数字使用

时间:2016-04-10 01:05:55

标签: objective-c nsdictionary

我使用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的深层副本?

1 个答案:

答案 0 :(得分:1)

  

虽然NSDictionary和CFDictionary对象允许它们的键是任何类型的对象,但如果键不是字符串对象,则集合不是属性列表对象。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html#//apple_ref/doc/uid/10000048i-CH3-54303

您无法使用非字符串键复制属性列表,因为这不是属性列表。

只需遍历字典并手动复制项目。

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中包含组件。)