Should you use 'isEqual' or '=='?

血红的双手。 提交于 2019-11-26 17:16:59

问题


I saw a couple of questions here on SO, with ansers including the function isEqual: instead of the standard ==.

So far, I have only learned to use the ==, so I'm wondering what's better to use, what are the pros and cons of each? When should you use them?

Thank you.


回答1:


They do different things; so you need to use the appropriate one:

Consider, if you will:

NSString *a = @"Hello!";
NSString *b = a;
NSString *c = [a mutableCopy];

if (a == b) NSLog(@"This prints");
if (b == c) NSLog(@"This doesn't");
if ([a isEqual:c]) NSLog(@"This does");

In other words; == merely checks if two pointers point to the same place, and therefore are the same object; isEqual: checks if the two objects are equal; in this case a and b are the same string, while c is a new string that is equal to a, in that it has the same characters in the same order; but it has a different class and a different address.

You'll almost always want to use isEqual: for objects, and, if they have it, a more specific comparator if they are of the same class (isEqualToString:, for example).

== on the other hand you should probably only use for integer data types. (They make little sense for objects, and less for floating point numbers.)




回答2:


isEqual will compare objects according to the method written for the receiver object

== compares the addresses of Objects (or their values for C type variables like ints

This means for say NSStrings == compares the address but isEquals: will look at the values of the string objects and so does something similar to strcmp

Note that many strings are interned so that their addresses are the same if their data is the same so == can appear to work in test cases.



来源:https://stackoverflow.com/questions/3741281/should-you-use-isequal-or

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