比较两个实例对象是否相同的方法

创建一个EOCPerson类,重写NSObject协议中的-(BOOL)isEqual:(id)object和-(NSUInteger)hash方法,方法的具体实现如下

EOCPerson.h

#import 

@interface EOCPerson : NSObject

@property(nonatomic,copy) NSString *firstName;

@property(nonatomic,copy) NSString *lastName;

@property(nonatomic,assign) NSUInteger age;

@end

EOCPerson.m

#import "EOCPerson.h"

@implementation EOCPerson

-(BOOL)isEqual:(id)object
{
    if (self == object) return YES;
    if ([self class] != [object class]) return NO;

    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
{
    NSUInteger firstNameHash = [_firstName hash];
    NSUInteger lastNameHash = [_lastName hash];
    NSUInteger ageHash = _age;
    return firstNameHash^lastNameHash^ageHash;
}

@end

要点

  • 相同的对象具有相同的hash码。
  • 地址相同的两个实例对象相同。
  • [_firstName hash]计算字符串的hash码

复习

^按位异或:

复习一下按位异或
1^2 = 3
2^3 = 1
3^4= 7
...

把数字转化为二进制:

1 = 001
2 = 010
3 = 011
4 = 100

按位异或操作解析:

1^2 =  001
       010
      ------
       011
    = 3
2^3 =  010
       011
      ------
       001
    = 1
3^4 =  011
       100
      ------
       111
    = 7

你可能感兴趣的:(iOS基础(OC))