NSArray index of last object discrepancy

◇◆丶佛笑我妖孽 提交于 2019-12-01 08:15:55

问题


Below is an example containing two arrays that return different indices for their lastObject.

NSMutableArray *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!


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/7135183/nsarray-index-of-last-object-discrepancy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!