如何对具有嵌套数组/字典的 NSArray 和 NSDictionary 进行真正的深度复制?
问题:有没有一种方法可以使用现有的 Objective-C 方法来对 NSDictionary 或 NSArray 进行完整的深层复制,而它们本身也有嵌套的字典或数组?
也就是说,我读到问题可能是当它遇到嵌套字典或数组时,它仅复制指向嵌套项目的指针,而不是真正复制该项目。
背景:作为我的一个例子,我尝试使用 NSUserDefaults 加载/保存以下配置,并且在加载时需要将从 NSUserDefault 获取的不可变副本转换为可变副本,然后再进行更改。
- 项目(NSDictionary)
- 项目(NSDictionary)
- aString: NSString
- aString2:NSString
- 日期:NSDate
- aDate2:NSDate
- aBool: BOOL
- aTI1:NSTimeInterval
- aTI2:NSTimeInterval
- 关键字 (NSArray)
- 关键字:NSString
- 关键字:NSString
- 项目(NSDictionary)
Question: Is there a way to use existing objective-c methods to do a full deep copy of a NSDictionary or NSArray, that themselves have nested dictionaries or arrays within them?
That is I have read the problem may be when it hits a nested dictionary or array it only copies the pointer to the nested item, and not copy the item truely.
Background: So as an example for me I'm trying to load/save the following config with NSUserDefaults and when loading need to convert the immutable copies one gets from NSUserDefault to mutable prior to making changes.
- Items (NSDictionary)
- Item (NSDictionary)
- aString: NSString
- aString2: NSString
- aDate: NSDate
- aDate2: NSDate
- aBool: BOOL
- aTI1: NSTimeInterval
- aTI2: NSTimeInterval
- Keywords (NSArray)
- keyword: NSString
- keyword: NSString
- Item (NSDictionary)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
几年前,我出于完全相同的原因编写了一些类别方法,将整个用户默认树转换为可变的。它们就在这里——使用它们需要您自担风险! :-)
A couple of years ago, I wrote a few category methods for exactly the same reason, transforming a whole tree of user defaults to mutable. Here they are - use them at your own risk! :-)
我认为这样的事情应该有效。
I think something like this should work.
进行深度复制的简单方法是使用 CFPropertyListCreateDeepCopy。下面是示例(使用 ARC):
本示例中的原始字典是 NSDictionary
CFPropertyListRef,只要 CFPropertyListRef 的顶级实体是 CFDictionary,就可以简单地转换为 NSDictionary。
The easy way for a DEEP copy is to simply use CFPropertyListCreateDeepCopy. Here is example (with ARC):
my originalDictionary in this example is an NSDictionary
CFPropertyListRef can simply be cast to NSDictionary as long as the top level entity of the CFPropertyListRef is a CFDictionary.
如果有人想要可变副本,请使用以下代码:
NSMutableDictionary *newDictionary = (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)dict, kCFPropertyListMutableContainers));
If someone want the mutable copy then please use below code:
NSMutableDictionary *newDictionary = (NSMutableDictionary *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)dict, kCFPropertyListMutableContainers));