我正在尝试创建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 …Run Code Online (Sandbox Code Playgroud) 我有一个NSMutableArray自定义对象(基于NSObject),我想复制到一个新的数组.但我希望它是一个深刻的副本.
我该怎么做呢?我是否需要在自定义对象中实现NSCopying协议?
谢谢
我无法弄清楚造成这种情况的原因.基本上,一些不同的"任务"在我的应用程序中相互冲突.当我按下按钮时,它运行此代码就好了:
PalAppDelegate *dataCenter = (PalAppDelegate *)[[UIApplication sharedApplication] delegate];
[dataCenter.colourPalettesContainer addObject:[NSNumber numberWithInt:5]];
Run Code Online (Sandbox Code Playgroud)
它可以像我喜欢的那样多次这样做.但是,当我执行另一项任务(以及导致这种情况发生的一些任务)时,这涉及此代码:
PalAppDelegate *dataCenter = (PalAppDelegate *)[[UIApplication sharedApplication] delegate];
[dataCenter.colourPalettesContainer removeObjectAtIndex:touchDownID];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:dataCenter.colourPalettesContainer forKey:@"container"];
[prefs synchronize];
Run Code Online (Sandbox Code Playgroud)
然后:
dataCenter.colourPalettesContainer = [prefs objectForKey:@"container"];
Run Code Online (Sandbox Code Playgroud)
当我在此之后再次运行第一个代码时,它会导致"发送到不可变对象的变异方法"错误.我怎么能阻止这个?
编辑:所以我从下面的一些答案中找到了问题.有没有人有不同的做法,他们建议?