2016-01-20 89 views
0

我定义类用户和用户拥有的丝束构件可变因素 - >NSString* name , NSSString* pass 我想通过NSSet Conllection将它们存储所以,我重写 - (NSUInteger)散列法等下列如何正确覆盖HashCode方法?

-(NSUIntegar) hash 
{ 
     NSLog(@"Hash Method %@",[self class]); 
     NSUInteger nameHash = name == nil ? 0 : [name hash]; 
     NSUInteger passHash = pass == nil ? 0 : [pass hash]; 
     return nameHash * 31 + passHash; 
} 

的main.m文件

NSSet* set = [NSSet setWithObjects: 
        [[User alloc] initWithName:@"nike" pass:@"123"], 
        [[User alloc] initWithName:@"nool" pass:@"456"], 
        [[User alloc] initWithName:@"boow" pass:@"124"], 
        [[User alloc] initWithName:@"enla" pass:@"124"], 
        [[User alloc] initWithName:@"boow" pass:@"124"],//same as member 3 
        nil]; 
    NSLog(@"set count = %ld",[set count]); 
    NSLog(@"%@",NSCollectionToString(set)); 

NSCollectionToString(ID集合)

NSString* NSCollectionToString(id collection) 
{ 

NSMutableString* result = [NSMutableString stringWithFormat: 
          @"["]; 
for (id object in collection) { 
    [result appendString:[object description]]; 
    [result appendString:@","]; 
} 
NSUInteger len = [result length]; 

[result deleteCharactersInRange:NSMakeRange(len - 1, 1)]; 
[result appendString:@"]"]; 
return result; 
} 

但是控制台输出:集数= 5 为什么不4?哪里错了?

回答

1

您需要覆盖这两个散列函数和isEqual:方法。

根据isEqual,散列函数必须为任意两个相等的对象返回相同的散列值。它根据isEqual返回不相等的对象的不同值,但除性能外,这不是必需的。默认的isEqual函数只是比较对象指针,所以具有相同数据比较的两个对象不相等。这就是为什么您的两个具有相同数据的对象都被添加到该集合中。