Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Index of an Object from NSArray?

People also ask

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is NSArray Objective C?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

Can NSArray contain nil?

arrays can't contain nil.


The index returned by indexOfObject will be the first index for an occurence of your object. Equality is tested using isEqual method.
The garbage value you get is probably equal to NSNotFound.
Try testing anIndex against it. The number you are looking for isn't probably in your array :

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

or log the content of the array to be sure :

NSLog(@"%@", myArray);

Folks,

When an object is not found in the array the indexOfObject method does NOT return a 'garbage' value. Many systems return an index of -1 if the item is not found.

However, on IOS - because the indexOfObject returns an UNSIGNED int (aka NSUInteger) the returned index must be greater than or equal to zero. Since 'zero' is a valid index there is no way to indicate to the caller that the object was not found -- except by returning an agreed upon constant value that we all can test upon. This constant agreed upon value is called NSNotFound.

The method:

- (NSUInteger)indexOfObject:(id)anObject;

will return NSNotFound if the object was not in the array. NSNotFound is a very large POSITIVE integer (usually 1 minus the maximum int on the platform).


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);

Its giving the correct output, may be u have done something wrong with storing objects in ur array.


Try this:

NSArray's indexOfObject: method. Such as the following:

NSUInteger fooIndex = [someArray indexOfObject: someObject];