Objective-C - NSObject isEqual,vs. ==比较? [英] Objective-C -- NSObject isEqual, vs. == comparison?

查看:234
本文介绍了Objective-C - NSObject isEqual,vs. ==比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

比较Obj-c中的对象

有什么区别在这两种检查对象相等性的方法之间:

What the difference is between these two methods of checking for object equality:

UIButton *btn1 = [[UIButton alloc] init];
UIButton *btn2 = [[UIButton alloc] init];

有什么区别:

if (btn1 == btn2) {
  // Run some code
}

if ([btn1 isEqual:btn2]) {
  // Run some code
}


推荐答案

第一个方式比较指针,而第二种方式比较对象。

The first way compares pointers, while the second way compares objects.

也就是说,第一种方式是比较指针是否具有相同的值。在这种情况下,它们可能不会,在第二种情况下,将比较对象。因为它们的初始化方式与它们相同的方式相同。 (注意,似乎使用 UIButton 的实现isEqual:,结果始终为false。)

That is, the first way compares if the pointers have the same value. In this case it is likely that they don't, in the second case the objects will be compared. Since they are initialized the same way they could be equal. (Note, it appears that with the UIButton's implementation of isEqual: the result is always false.)

在大多数情况下,使用 == 不是你想要的。但是,什么是合适的取决于你的目标。

In most cases using == is not what you want. However, what is appropriate depends on your objective.

这篇关于Objective-C - NSObject isEqual,vs. ==比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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