• Effective Objective-C 2.0 — 第8条:理解“对象等同性”这一概念


    第8条:理解“对象等同性”这一概念

    • 若想检测对象的等同性,请提供“isEqual”与 hash 方法
    • 相同的对象必须具有相同哈希码,但是两个哈希码相同的对象却未必相同。
    • 不要盲目地逐个检测每条属性,而是应该依照具体需求来制定检测方案。、判定个数、唯一标识符等等
    • 编写hash 方法时,应该使用计算速度快而且哈希码碰撞几率低的算法。

    按操作符比较的是两个指针本身,而不是其所指的对象

    NSString *foo = @"Badger 123";
    NSString *bar = [NSStringstringWithFormat:@"Badger %i", 123];
    BOOL equalA = (foo == bar);  //  equalA = NO
    BOOL equalB = [foo isEqual:bar]; // equalB = YES
    BOOL equalC = [foo isEqualToString:bar]; //equalC = YES  传递对象必须是NSString,比 isEqual 快

    NSObject协议中 判断等同性的关键方法

    - (BOOL)isEqual:(id)object;

    - (NSUInteger)hash;

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

  • 相关阅读:
    C#基于引用创建单链表
    锻炼自己的思维模式
    [数据结构]C#基于数组实现泛型顺序表
    DEV Express
    [LeetCode] Combinations (bfs bad、dfs 递归 accept)
    [LeetCode] Wildcard Matching
    [LeetCode] Remove Duplicates from Sorted List II
    [LeetCode] Partition List
    [LeetCode] Scramble String(树的问题最易用递归)
    [LeetCode] Decode Ways(DP)
  • 原文地址:https://www.cnblogs.com/IDRI/p/5072011.html
Copyright © 2020-2023  润新知