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;

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

 

你可能感兴趣的:(Effective Objective-C 2.0 — 第8条:理解“对象等同性”这一概念)