iOS开发

iOS中isEqual的重写的实现方法

2021-10-18  本文已影响0人  iOS祈峰

前言

不积跬步无以至千里,不积小流无以成江海。学如逆水行舟,不进则退。我是平平无奇游荡于各平台的搬运工。今天给大家讲讲iOS如何来实现isEqual的重写。废话不多说,直接给大家上干货,希望能对你有所帮助,优秀的人已经点赞了。

一、重写hash的方法

    - (NSUInteger)hash {
    NSUInteger subhashes[] = {[self.property1 hash], [self.property2 hash], [self.property3 hash]};
    
    NSUInteger result = subhashes[0];
    
    for (int ii = 1; ii < 3; ++ii) {
        unsigned long long base = (((unsigned long long)result) << 32 | subhashes[ii]);
        base = (~base) + (base << 18);
        base ^= (base >> 31);
        base *=  21;
        base ^= (base >> 11);
        base += (base << 6);
        base ^= (base >> 22);
        result = base; 
            } 
            return result;
            }

示例:

@interface Person : NSObject
 
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSDate *birthday;
 
@end


- (BOOL)isEqual:(id)object {
    if (self == object) {
        return YES;
    }
 
    if (![object isKindOfClass:[Person class]]) {
        return NO;
    }
 
    return [self isEqualToPerson:(Person *)object];
}
 
- (BOOL)isEqualToPerson:(Person *)person {
    if (!person) {
        return NO;
    }
 
    BOOL haveEqualNames = (!self.name && !person.name) || [self.name isEqualToString:person.name];
    BOOL haveEqualBirthdays = (!self.birthday && !person.birthday) || [self.birthday isEqualToDate:person.birthday];
    return haveEqualNames && haveEqualBirthdays;
}

二、重写 isEqual

    - (BOOL)isEqual:(PersonModel *)object {
    if (self == object) {
        return YES;
    }
    else if (self == nil || object == nil || ![object isKindOfClass:[self class]]) {
        return NO;
    }
    
    return
    (_property1 == object->_property1 ? YES : [_property1 isEqual:object->_property1]) &&
    (_property2 == object->_property2 ? YES : [_property2 isEqual:object->_property2]) &&
    (_property3 == object->_property3 ? YES : [_property3 isEqual:object->_property3]);
}

三、hash 与判等的关系

更多iOS学习请关注主页哦!!!加入圈子获取哦

收录自:地址

上一篇下一篇

猜你喜欢

热点阅读