Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only one instance of an object from an NSMutableArray?

The Apple documentation says that the - (void)removeObject:(id)anObject method removes all occurrences of the given object from an NSMutableArray.

Is there a way to remove only one occurrence of the object from the array?

like image 501
gossainapps Avatar asked Aug 15 '12 04:08

gossainapps


2 Answers

If you have a particular instance that you want removed, which has a unique memory address but would otherwise compare equal to other instances, you would use removeObjectIdenticalTo:.

If you want to remove the first object in the array that fits the bill, use indexOfObject:, which finds the lowest index, followed by removeObjectAtIndex: You can also use indexesOfObjectsPassingTest: to get the list of all indexes that contain equal objects, as an NSIndexSet, and then pick one out from there -- perhaps lastIndex, e.g.

like image 140
jscs Avatar answered Sep 21 '22 12:09

jscs


It is really simple: [yourArray removeObjectAtIndex:[yourArray indexOfObject:yourObject]]

like image 30
Luan Nguyen Avatar answered Sep 20 '22 12:09

Luan Nguyen