Next: NSMutableArray Up: NSArray Previous: Second Way - Using

Searching for an Object

If you want to check whether an NSArray contains a certain object or not, you should use the -containsObject: method, as in the following example:
NSArray *array;

array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",
                                   @"Luciano", @"Silvia", nil];

if ([array containsObject: @"Nicola"]) // YES
  {
    // Do something
  }
-containsObject: compares the objects using -isEqual:, which is usually what you want: eg, two NSString objects containing the same UNICODE characters would be considered equal, even if they are not the same object.

To get the index of an object, you can use -indexOfObject:, which returns the index of the object (better, of an object equal to the argument), or the constant NSNotFound if no object equal to the argument can be found in the array, as in the following example:

NSArray *array;
int i, j;

array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",
                                   @"Luciano", @"Silvia", nil];

i = [array indexOfObject: @"Margherita"]) // 1
j = [array indexOfObject: @"Luca"]) // NSNotFound



Nicola 2002-01-13