简体   繁体   中英

NSMutableArray removeObjectAtIndex: Behaviour

I have an NSMutableArray which I assign with:

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];

I'm removing selectedElement from this array, but seeing some bizarre behaviour in the debugger. After initializing the array, by setting a breakpoint before removing selectedElement , I see this:

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

)

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

I;m trying to remove the object with with:

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]);

I don't understand why my object isn't removed. It's like I'm missing the point.

self.currentScene.elements is an array. So you're creating a new array with that array inside it. The only item in newArray is self.currentScene.elements . If you want to create a mutable copy of self.currentScene.elements , just use mutableCopy .

You have an array that contains one object, which is another array. newElements only has one valid index, and that is 0 . You need to change your first line to look like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM