#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