你应该使用'isEqual'还是'=='? [英] Should you use 'isEqual' or '=='?

查看:251
本文介绍了你应该使用'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.)

这篇关于你应该使用'isEqual'还是'=='?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆