NSNumber comparision iOS SDK 4.2 vs 5, in Objective-C?

女生的网名这么多〃 提交于 2019-12-25 04:06:55

问题


I found a bug in my app: The logic was that I was comparing two NSNumbers using "==", and I believe it used to work. But it no longer passes on iOS sdk 5, so I need to use isEqualToNumber instead.

Can anyone with iOS sdk 4.2 please try and run the following code and give me the result. I tried to revert to older Xcode to test it myself, but I was not able to do that.

NSNumber *num1 = [NSNumber numberWithInt:100];
NSNumber *num2 = [NSNumber numberWithInt:100];

if (num1 == num2)
{
    NSLog(@"== YES");
}
else
{
    NSLog(@"== NO");
}

回答1:


The isEqualToNumber is the correct solution here. The fact that it used to work is purely an implementation detail with how the numbers were cached by the system internally. You should never (read probably not what you really want to do) compare objects using ==. == on objects will compare their memory address, not if they're actually equal.



来源:https://stackoverflow.com/questions/8161780/nsnumber-comparision-ios-sdk-4-2-vs-5-in-objective-c

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