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ものです。たとえば、Mac OS X 10.7.5 ソースの ForFoundationOnly.h を参照してください。NSNumberfloatdouble

#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 に答える