NSMutableArray正在影响另一个NSMutableArray?

时间:2017-08-31 04:54:39

标签: ios objective-c arrays

我有两个NSMutableArray,两者都获得相同的数据。我的问题是,当我将相同的数据分配给来自不同字典的可变数组并在一个NSMutableArray上执行操作时,它会影响两个数组。

当我第一次执行replaceObjectAtIndex:WithObject:之类的操作时,数组不会受到影响,但是当调用第二个替换时,两个数组都具有替换值。我认为这是一个参考问题。

有没有人有解决方案?

NSMutableArrays的名称为helper.urlsRecordinghelper.holdingArr

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict setValue:outputFileURL forKey:@"URL"];
[dict setValue:@"1" forKey:@"index"];
[dict2 setValue:outputFileURL forKey:@"URL"];
[dict2 setValue:@"1" forKey:@"index"];
[helper.urlsRecording addObject:dict];
[helper.holdingArr addObject:dict2];


[helper.urlsRecording replaceObjectAtIndex:button.tag withObject:urlAr];//When this called second time, both the arrays is effected(helper.urlsRecording as well as helper.holdingArr).

如何防止将引用复制到另一个数组?

按钮点击:

if([button isSelected] == NO){

     NSLog(@"Url Recording : %@",helper.urlsRecording);
     [[helper.urlsRecording objectAtIndex:button.tag] removeObjectForKey:@"URL"];
     button.selected = YES;
     NSLog(@"Url Recording : %@",helper.urlsRecording);
}
else{
     [helper.urlsRecording replaceObjectAtIndex:button.tag withObject:[helper.holdingArr objectAtIndex:button.tag]];
     button.selected = NO;
     NSLog(@"Url Recording : %@",helper.urlsRecording);

 }

注意:NSMutableArray在要访问的类中全局定义。

2 个答案:

答案 0 :(得分:2)

这是因为两个字典的实例值都相同。

首先创建一个mutableDictionary,如下所示

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:outputFileURL forKey:@"URL"];
[dict setValue:@"1" forKey:@"index"];

通过mutableCopy创建第二个字典,因此两个实例都不同。

NSMutableDictionary *dict2 = [dict mutableCopy];

之后,您可以将其添加到NSMutableArray并相应更新。

答案 1 :(得分:0)

获取copy / mutableCopy词典&然后将对象添加到MutableArray

[helper.urlsRecording addObject:[dict copy]];
[helper.holdingArr addObject:[dict2 copy]];