2

这是我的 isEqual 和哈希自定义运算符

- (BOOL)isEqual:(id)object;
{
    BGSearchParameter * theOther = (BGSearchParameter *)object;

    BOOL isTheOtherEqual;
    isTheOtherEqual = isTheOtherEqual && [self.Location isEqual:theOther.Location];
    isTheOtherEqual = isTheOtherEqual && [self.keyword isEqual:theOther.keyword];
    isTheOtherEqual = isTheOtherEqual && (self.Distance == theOther.Distance);
    isTheOtherEqual = isTheOtherEqual && (self.SortByWhat == theOther.SortByWhat);
    isTheOtherEqual = isTheOtherEqual && (self.startFrom == theOther.startFrom);
    isTheOtherEqual = isTheOtherEqual && (self.numberOfIDstoGrab == theOther.numberOfIDstoGrab);

    return isTheOtherEqual;
}
- (NSUInteger)hash
{
    NSUInteger returnValue=0;
    returnValue ^= self.Location.hash;
    returnValue ^= self.keyword.hash;

    return returnValue;
}

那个做这项工作。但是,假设我想将距离和 startfrom 合并到哈希中。

我想我会简单地添加:

returnValue ^= self.Distance;

这是一个错误,因为它不兼容。

那么我应该怎么做呢?

4

3 回答 3

4

我最终把数字变成了 NSNumber 并得到了哈希:

   returnValue ^= @(self.Distance).hash;
   returnValue ^= @(self.SortByWhat).hash;
   returnValue ^= @(self.startFrom).hash;
   returnValue ^= @(self.numberOfIDstoGrab).hash;

马丁的回答很好。但是,结果应该是一样的,我不想实现另一个复杂的功能。

于 2012-10-21T14:05:33.063 回答
2

这是CFNumber/NSNumber用作floatdouble值的散列值,例如参见 Mac OS X 10.7.5 Source 中的ForFoundationOnly.h

#define HASHFACTOR 2654435761U

CF_INLINE CFHashCode _CFHashDouble(double d) {
    double dInt;
    if (d < 0) d = -d;
    dInt = floor(d+0.5);
    CFHashCode integralHash = HASHFACTOR * (CFHashCode)fmod(dInt, (double)ULONG_MAX);
    return (CFHashCode)(integralHash + (CFHashCode)((d - dInt) * ULONG_MAX));
}

CFHashCode定义为

typedef unsigned long CFHashCode;
于 2012-10-21T10:13:49.853 回答
-1

试试这个:

static NSUInteger doubleHash(float value) {
    return *(NSUInteger *)&value;//gets bits
}

注意转换为浮动。它会降低精度,但 sizeof(float)==sizeof(NSUInteger)。

于 2013-04-27T02:51:21.663 回答