Friday, May 31, 2013

NSArray indexOfObject example in Objective C (iOS).


NSArray indexOfObject

Returns the lowest index whose corresponding array value is equal to a given object.

- (NSUInteger)indexOfObject:(id)anObject

Parameters
anObject
An object.

Return Value of [NSArray indexOfObject]
The lowest index whose corresponding array value is equal to anObject. If none of the objects in the array is equal to anObject, returns NSNotFound.

Discussion of [NSArray indexOfObject]
Starting at index 0, each element of the array is sent an isEqual: message until a match is found or the end of the array is reached. This method passes the anObject parameter to each isEqual: message. Objects are considered equal if isEqual: (declared in the NSObject protocol) returns YES.

NSArray indexOfObject example.
NSNumber *num=[NSNumber numberWithInteger:56];
NSInteger Aindex=[myArray indexOfObject:num];
if(NSNotFound == Aindex) {
    NSLog(@"not found");
}

Example of [NSArray indexOfObject].
NSNumber *num1 = [NSNumber numberWithInt:56];
    NSNumber *num2 = [NSNumber numberWithInt:57];
    NSNumber *num3 = [NSNumber numberWithInt:58];
    NSMutableArray *myArray = [NSMutableArray arrayWithObjects:num1,num2,num3,nil];
    NSNumber *num=[NSNumber numberWithInteger:58];

    NSInteger Aindex=[myArray indexOfObject:num];

    NSLog(@" %d",Aindex);

NSArray indexOfObject example.
NSArray *a = [NSArray arrayWithObjects:@"Foo", @"Bar", @"Baz", nil];
NSLog(@"At index %i", [a indexOfObject:@"Bar"]);

End of NSArray indexOfObject example article.