ios - 对默认的 isEqual 和 hash 实现感到困惑

标签 ios objective-c

我知道我可以重写 hash 和 isEqual 来检查 2 个实例是否相等。 Xcode 有默认的片段和文档 https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectComparison.html如下

- (BOOL)isEqual:(id)other
{
    if (other == self) {
        return YES;
    } else if (![super isEqual:other]) { //WHAT is this line mean ?
        return NO;
    } else {
        return <#comparison expression#>;
    }
}

- (NSUInteger)hash
{
    return <#hash expression#>;
}

好的,

  1. other == self 检查两个对象的指针。

  2. if ![super isEqual:other],这行是什么意思?如果 super 对象不等于 other,返回 NO ?然后一直返回NO,第3步不会执行。

我错了吗?

谢谢。

最佳答案

这是类层次结构中的典型实现,也就是说,如果您的类派生自具有自己有意义的 isEqual: 实现的父类(super class)。在那种情况下,让父类(super class)测试公共(public)属性的相等性是明智的。如果公共(public)部分不相等,则派生对象不可能相等。

如果您直接从 NSObject 派生,则不需要它。

实际上,您还需要一个额外的步骤:

- (BOOL)isEqual:(id)other
{
    if (other == self) {
        return YES;
    } else if (![super isEqual:other]) {
        return NO;
    } else if (![other isKindOfClass:[MyClass class]]) {
        return NO; // comparing incompatible objects 
    } else {
        MyClass *myOther = (MyClass *) other;
        return <#compare between self and myOther#>;
    }
}

关于ios - 对默认的 isEqual 和 hash 实现感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36593038/

相关文章:

ios - HealthKit 示例元数据修改

ios - 解析错误代码 206 : Cannot modify user (Parse Server)

ios - 使用 REST API 对 Parse.com 进行复合查询

ios - 如何在导航 Controller 中将数据从一个 View 传递到另一个 View

objective-c - 如何在 objective-c 中编写非阻塞方法

ios - UIAlertView 的标题被传递到不同屏幕上的 UITextField

objective-c - iOS 4 上的推送通知如何显示?

ios - 存档时在iOS中找不到“Realm/Realm.h”文件

ios - 德语的 Localizable.strings

ios - 使用清洁委托(delegate)模式