Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an array contains a certain object (iOS)

I need to check if a certain array contains a certain object, and if it does, delete that object. If it hasn't got that object, the funciton is suposed to add it into the array. The problem is that the object is always added because the checking statement always return false.

Here's my current function:

- (void) myFunction:(NSString *)parameter {

    if (![myMutableArray containsObject:parameter]) {

        [myMutableArray addObject:parameter];
        NSLog(@"%@ added", parameter);

    } else {

        [myMutableArray removeObject:parameter];
        NSLog(@"%@ deleted", parameter);

    }
}
like image 339
iosdevrocks Avatar asked Jan 16 '13 19:01

iosdevrocks


People also ask

How do you check if an array contains a specific item?

Using includes() Method: If array contains an object/element can be determined by using includes() method. This method returns true if the array contains the object/element else return false.

How do you check if an object is in an array Swift?

The contains() method checks whether the specified element is present in the array or not.

How do you check if an array of objects contains a value?

Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .


1 Answers

containsObject is calling isEqual on each of the object in the arrays. What type of object are you checking for? If it's a custom object, override and implement the method isEqual.

I'm guessing you're trying to check the value of the object, but containsObject is actually calling isEqual which is comparing the reference to the object, and not its actual value.

like image 51
Rohan Agarwal Avatar answered Oct 08 '22 07:10

Rohan Agarwal