iOS 객체 판단 동일

2326 단어

==

 , == ; 
 , == ( )

isEqual

UIColor *color1 = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
UIColor *color2 = [UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0];
NSLog(@"color1 == color2 = %@", color1 == color2 ? @"YES" : @"NO");
NSLog(@"[color1 isEqual:color2] = %@", [color1 isEqual:color2] ? @"YES" : @"NO");

color1 == color2 = NO
[color1 isEqual:color2] = YES

 OC     
    isEqual  NO        isEqual 

다시 쓰기 isEqual

@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *age;
@property (nonatomic, strong) NSDate *date;
@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.age && !person.age) || [self.age isEqualToString:person.age];
    
    return haveEqualNames && haveEqualBirthdays;
}

왜 대상의hash값을 다시 써야 합니까

hash NSSet NSDictionary key 
 key hash 

    Person *person1 = [Person personWithName:@"Joe" age:@"32"];
    Person *  = [Person personWithName:@"Joe" age:@"32"];
    Person *person3 = [Person personWithName:@"Joe" age:@"33"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:@"1" forKey:person1];
    [dict setObject:@"2" forKey:person2];
    [dict setObject:@"3" forKey:person3];
    NSLog(@"person1----%@", [dict objectForKey:person1]);
    NSLog(@"person2----%@", [dict objectForKey:person2]);
    NSLog(@"person3----%@", [dict objectForKey:person3]);
    NSLog(@"dict count: %ld", dict.count);
  3。 isEqual   person1 person2    2。   hash   
- (NSUInteger)hash {
    return [self.name hash] ^ [self.birthday hash];
}

참고 자료

좋은 웹페이지 즐겨찾기