Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...