user4951
user4951

Reputation: 33080

How to remove at most one object from nsmutablearray?

I want to insert a bunch of objects into a NSMutableArray. Then I would remove them one by one when the time fits. Every inserted objects must be removed.

However, if I have several copies of the same object, I just want to remove one of them.

How would I do that?

Upvotes: 0

Views: 63

Answers (5)

Marcelo
Marcelo

Reputation: 9944

NSMutableArray *arr = [@[@1, @1, @5, @6, @5] mutableCopy]; // a copy of your array
NSMutableSet *removedObjects = [NSMutableSet setWithArray:arr];
for (id obj in removedObjects) {
    [arr removeObjectAtIndex:[arr indexOfObject:obj]]; // removes the first identical object
}

Also note that if your array is filled with custom objects, you need to implements hash and isEqual: so the comparisons can work.

Upvotes: 3

meth
meth

Reputation: 1885

i prefer using index of object; it will return the index of object first appeared in the array

 NSMutableArray * first = [@[@"2",@"3",@"4",@"5"] mutableCopy];//your first array

    NSMutableArray * willBeAppend =  [@[@"2",@"3",@"4",@"5"] mutableCopy];//new objects to append

    [first addObjectsFromArray:willBeAppend];//append new objects

    id objectToBeRemoved = @"3";// object will be removed

    NSInteger objIx = [first indexOfObject:objectToBeRemoved];// index of object

    if (objIx != NSNotFound) {

        [first removeObjectAtIndex:objIx]; //remove object


        NSLog(@"%@",first);

    }

Upvotes: 0

Sulthan
Sulthan

Reputation: 130102

I don't think it's a good design for [NSMutableArray removeObject:] to remove all the occurences but we can avoid it by first getting an index using indexOfObject: and then removing the object using removeObjectAtIndex:

Upvotes: 1

JeremyP
JeremyP

Reputation: 86651

[myMutableArray removeObjectAtIndex: 0];

or

[myMutableArray removeLastObject];

To remove the first and last objects respectively.

Upvotes: 1

Fonix
Fonix

Reputation: 11597

are any of these functions what you are looking for?

[array removeObjectAtIndex:(NSUInteger)];
[array removeLastObject];
[array removeObject:(id)];

Upvotes: 1

Related Questions