你应该使用'isEqual'还是'=='?
我在这里看到了一些问题,其中ansers包括函数 isEqual:
而不是标准 ==
。
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?
谢谢。
做不同的事情;所以你需要使用适当的:
They do different things; so you need to use the appropriate one:
如果你愿意,请考虑:
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");
换句话说: ==
只检查两个指针是否指向同一个地方,因此是同一个对象; isEqual:
检查两个对象是否相等;在这种情况下 a
和 b
是相同的字符串,而 c
是一个等于 a
的新字符串,因为它具有相同顺序的相同字符;但它有一个不同的类和不同的地址。
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.
你几乎总是想使用 isEqual:
对象,如果它们具有相同的类,则它们具有更具体的比较器(例如 isEqualToString:
)。
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.)