2017-08-31 41 views
-1

我有兩個NSMutableArray s,都獲得相同的數據。我的問題是,當我將相同的數據分配給來自不同字典的可變數組並且在一個NSMutableArray上執行操作時,它會影響這兩個數組。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在一個類中定義的全局訪問。

+0

你是如何初始化這兩個數組? –

+0

@ReinierMelian檢查編輯請 – Williams

+0

是的,我正在初始化他們這就是爲什麼我得到的數據。 – Williams

回答

3

這是因爲您的實例值對於這兩個字典都是相同的。

所以首先創建一個mutableDictionary像下面

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

並通過mutableCopy創建第二個字典,所以例如將兩個不同的。

NSMutableDictionary *dict2 = [dict mutableCopy]; 

之後,你可以在將它們添加到NSMutableArray並相應更新。

+0

問題是一樣的,第二次數據被引用到數組相同,當第二次點擊按鈕時引用仍然是相同的。 – Williams

+0

你在做什麼按鈕點擊。給我看代碼 –

+0

檢查編輯請 – Williams

0

乘坐copy/mutableCopy字典&然後添加對象到MutableArray

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

我會試試這個。 – Williams

+0

okey。這對你有用嗎? –

+0

否bro。不工作。 – Williams

相關問題