NSArray index of last object discrepancy

断了今生、忘了曾经 提交于 2019-12-01 10:56:22

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.

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