2012-06-27 73 views
0

我有一個NSMutableArray我與分配:的NSMutableArray removeObjectAtIndex:行爲

NSMutableArray *newElements = [[NSMutableArray alloc] initWithObjects:self.currentScene.elements, nil]; 
//selectedElement is assigned somewhere above this, shouldn't be relevant since it's the same object as the one in the array 
int indexToRemove = [self.currentScene.elements indexOfObject:selectedElement]; 

我從這個數組刪除selectedElement,但看到在調試器中的一些怪異行爲。除去selectedElement之前初始化數組,通過設置一個斷點後,我看到:

po newElements 
(NSMutableArray *) $2 = 0x08c74e90 <__NSArrayM 0x8c74e90>(
<__NSArrayM 0x8c52e60>(
<StoryTextElement: 0x12ac6e00>, 
<StoryTextElement: 0x8ca1a50> 
) 

) 

(lldb) po selectedElement 
(StoryElement *) $3 = 0x08ca1a50 <StoryTextElement: 0x8ca1a50> 

我; M嘗試與刪除對象,具有:

NSLog(@"count: %d", [newElements count]); // prints count: 1 
[newElements removeObject:selectedElement]; 
NSLog(@"count: %d", [newElements count]); // prints count: 1 
[newElements removeObjectAtIndex:indexToRemove]; // throws an exception. indexToRemove is 1 in the debugger 
NSLog(@"count: %d", [newElements count]); 

我不明白爲什麼我的對象不會被刪除。這就像我錯過了這一點。

回答

1

你有一個包含一個對象的數組,它是另一個數組。 newElements只有一個有效索引,即0。你需要改變你的第一行看起來像

NSMutableArray *newElements = [[self.currentScene.elements mutableCopy] autorelease]; 
+0

哦,明顯的錯誤。謝謝,我從來沒有發現過。 – Echilon

2

self.currentScene.elements是一個數組。所以你正在用它裏面的數組創建一個新數組。 newArray中的唯一項目是self.currentScene.elements。如果您想創建self.currentScene.elements的可變副本,只需使用mutableCopy即可。

相關問題