NSData compare to NSData in percents

2019-02-15 22:44发布

问题:

I Have NSData *object1 and another NSData *object2. How can I compare this objects by what percentage they are similar? For example: Object1 similar to Object2 in - 99%. Thanks.

回答1:

Get the bytes in both cases and iterate through checking how many of them are equal.

uint8_t* bytes1 = (uint8_t*)[object1 bytes];
uint8_t* bytes2 = (uint8_t*)[object2 bytes];

NSUInteger sameCount = 0;
for (NSUInteger i = 0 ; i < MIN([object1 length], [object2 length]) ; ++i)
{
    if (bytes1[i] == bytes2[i])
    {
        sameCount++;
    }
}

double fractionSame = (double) sameCount / (double) MIN([object1 length], [object2 length]);

The above assumes if one data is longer than the other, you don't care about the excess.



回答2:

It really depends on the logic. If you are, for example, trying to compare images (and their data is stored as NSData) then you need to write image comparison algorithms. If it is some other kind of data, then you need to define that semantics first. If all else fails I think @JeremyP answer should suffice.



回答3:

There's no such thing for NSData. You'll need to write your own NSSortDescriptor thing, optimized for how you want to compare the contents of one NSData to another.

http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html