NSArray index of last object discrepancy
Below is an example containing two arrays that return different indices for their lastObject.
NSMu开发者_开发知识库tableArray *ary0 = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:[NSDecimalNumber decimalNumberWithString:@"2"],[NSDecimalNumber one], nil]];
NSLog(@"%d",[ary0 indexOfObject:[ary0 lastObject]]);
Logs 1, as expected.
NSMutableArray *ary1 = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:[NSDecimalNumber one],[NSDecimalNumber one], nil]];
NSLog(@"%d",[ary1 indexOfObject:[ary1 lastObject]]);
Logs 0.
I do not see how the index of the lastObject in ary1 is 0, even if there are two identical objects in ary1. Can someone please explain why this makes sense or point out the very silly mistake I'm making? Thanks!
You're not getting the index of the last object, you're getting the index of the first object that is equal to the last object. indexOfObject: is documented as searching from the first element of the array to the last, stopping when it finds a match.
You seem to be viewing two different steps as one coherent task. When you ask an array for the indexOfObject:
, it returns the first index for that object. And when you ask an array for its lastObject
, it returns the current last object. Since lastObject
just returns a normal object reference — and not something representing the general idea of "the last object" — you can't combine them to mean "the index of the last object."
So you are asking for the first index that contains an object equal to [NSDecimalNumber one]
(the last object in both arrays). The answer for the first array is that index 1 is the first one that contains that is equal to that. For the second array, the is that index 0 is the first one that contains an object equal to [NSDecimalNumber one]
.
Incidentally, if you do want the index of the last object in an array, it's guaranteed to be [array count] - 1
.
Try this:
NSLog(@"%p", [NSDecimalNumber one]);
NSLog(@"%p", [NSDecimalNumber one]);
You'll see both have the same address. They are the same object. When calling lastObject, you are getting an instance of an object that exists twice in the array, like you said. It exists at indexes 0 and 1. When you call indexOfObject, it returns the first index found: 0.
精彩评论