#import "ViewController.h" @interface ViewController () @end /** * "=="操做符比較出來的是兩個指針自己,而不是所指的對象 應該使用"isEqual"方法來判斷兩個對象的同等系 */ @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *foo = @"ZouJie 123"; NSString *bar = [NSString stringWithFormat:@"ZouJie %i",123]; BOOL equalA = (foo == bar); NSLog(@"equalA == %d",equalA);//NO BOOL equalB = [foo isEqual:bar]; NSLog(@"equalB == %d",equalB);//YES BOOL equalC = [foo isEqualToString:bar]; NSLog(@"equalC == %d",equalC);//YES } #pragma mark NSObject 中用於判斷等同性的關鍵方法 -(BOOL)isEqual:(id)object { return YES; } -(NSUInteger)hash { return 123; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end #import <Foundation/Foundation.h> @interface EocPerson : NSObject @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; @property (nonatomic, assign) NSUInteger age; @end #import "EocPerson.h" @implementation EocPerson -(BOOL)isEqual:(id)object { if (self == object) return YES; if ([self class]!=[object class]) return YES; EocPerson *otherPerson = (EocPerson *)object; if (![_firstName isEqualToString:otherPerson.firstName]) return NO; if (![_lastName isEqualToString:otherPerson.lastName]) return NO; if (_age != otherPerson.age) return NO; return YES; } /** * 若兩對象相等,則其哈希碼也想等,而哈希碼相同的對象卻未必相等 */ -(NSUInteger)hash { // return 1337; NSUInteger firstNameHash = [_firstName hash]; NSUInteger lastNameHash = [_lastName hash]; NSUInteger ageHash = _age; return firstNameHash ^ lastNameHash ^ ageHash;//這種作法既能保持較高效率,又能使生成的哈希碼至少位於必定範圍以內 //而不會過於頻繁的重複 } @end