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

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

So far, I have only learned how to use == , so I wonder what is better to use, what are the pros and cons of each of them? When should you use them?

Thanks.

+4
source share
2 answers

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

Consider if you:

 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; == just checks to see if two pointers point to the same place and, therefore, are the same object; isEqual: checks if two objects are equal; in this case, a and b are the same line, and c is the new line, which is equal to a , because it has the same characters in the same order; but it has a different class and a different address.

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

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

+9
source

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

== compares the addresses of objects (or their values ​​for variables of type C, such as ints

This means that NSStrings == compares the address, but isEquals: will look at the values ​​of string objects and therefore does something similar to strcmp

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

+1
source

All Articles