views:

57

answers:

3

is there a class available to check if an array doesnt contain an object? i want to do something like

if [(myarray doesntContain @"object")]

is this possible thanks

A: 

If you're dealing with an NSArray, your first port of call should probably be the Apple documentation for NSArray, and probably the method containsObject, there's an example in this question.

Rob
i know about contains objecti want to see if there isnt a specific object in the array and if there isnt to add one. i know how to add i just dont know how to check if an object is missing..
Alx
So invert the call to `containsObject` as Georg has indicated in his answer =)
Rob
+2  A: 

For NSArray use -containsObject::

if (![myarray containsObject:someObject]) {
    // ...
}
Georg Fritzsche
i know about contains objecti want to see if there isnt a specific object in the array and if there isnt to add one. i know how to add i just dont know how to check if an object is missing..
Alx
@Alx: Thats why the `!` is there, its basically *"if not (array containsObject)"*. There isn't a specific `-doesntContainObject:` as its trivial to use `!` or `== NO`.
Georg Fritzsche
sorry i didnt see that im sorry :(thanks alot btw..
Alx
however one small error i have if (![self.favoritesArray containsObject:@"added"]) { [self.favoritesArray addObject:@"added"]; } else if ([self.favoritesArray containsObject:@"added"]) { [self.favoritesArray removeObject:@"added"]; }this is my code and when i press the button it doesn remove the added option...
Alx
@Alx: You can't add or remove objects with a `NSArray`, use `NSMutableArray`. If you still have problems then, you should open a new question and add some more details. Also note that `if (!...) { ... } else { ... }` is sufficient (you don't have to test twice) and that maybe `NSMutableSet` would be a better fit for you.
Georg Fritzsche
i know and my array is a mutable one.
Alx
A: 

Use this:

if ([myarray indexOfObject:someObject] != NSNotFound) { // Or containsObject:someObject (as mentioned by Georg)
    [myarray addObject:someObject];
}
Tim van Elsloo
`-indexOfObject:` returns a zero-based index, thus your condition would be met if the first object in the array compares equal to `someObject`. `NSNotFound` is what the indices should be tested against.
Georg Fritzsche
Oh, yeah, I did never think about that... Thank you... Think I need to update my code now :P!
Tim van Elsloo