Hash value of NSDictionary

后端 未结 5 1870
温柔的废话
温柔的废话 2020-12-30 07:54

I ran into an issue, where I got the same hash value for different dictionaries. Maybe I\'m doing something obvious wrong, but I thought, objects with different content (a.k

5条回答
  •  萌比男神i
    2020-12-30 08:37

    A solution based on igor-kulagin's answer which is not order dependent:

    @implementation NSDictionary (Extensions)
    
    - (NSUInteger) hash
    {
        NSUInteger prime = 31;
        NSUInteger result = 1;
        for (NSObject *key in [[self allKeys] sortedArrayUsingSelector:@selector(compare:)]) {
            result = prime * result + [key hash];
            result = prime * result + [self[key] hash];
        }
        return result;
    }
    @end
    

    However, there is still a possibility of collision if the dictionary contains other dictionaries as values.

提交回复
热议问题