Search code examples
iosobjective-cnsarray

Objective C - NSArray's indexOfObject: not work


I use [items indexOfObject:items.lastObject] to get the last index, but this code returns nil. Why does this happen?

enter image description here


Solution

  • The first and last object in your array are both bar button items created with the system item of "fixed space".

    The result of calling indexOfObject: is 0, not nil. This means that the object is being found at index 0. indexOfObject: can't return nil. If an object isn't found, it returns the special value NSNotFound which is the unsigned value for -1.

    From the documentation for indexOfObject::

    Starting at index 0, each element of the array is passed as an argument to an isEqual: message sent to anObject until a match is found or the end of the array is reached. Objects are considered equal if isEqual: (declared in the NSObject protocol) returns YES.

    The implementation of UIBarButtonItem isEqual: will return YES if two bar button item instances are created with the same system item (and probably a few other properties as well).

    indexOfObject: is not based on the instance of the object, it's based on isEqual:.

    If you want to find the index of an object based on the identity (its address) of the object instead of isEqual:, use indexOfObjectIdenticalTo:.

    p [items indexOfObjectIdenticalTo:items.lastObject]
    

    will give you 6 instead of 0.