NSData compare to NSData in percents

2019-02-15 22:01发布

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.

3条回答
Melony?
2楼-- · 2019-02-15 22:38

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.

查看更多
够拽才男人
3楼-- · 2019-02-15 22:40

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.

查看更多
何必那么认真
4楼-- · 2019-02-15 22:58

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

查看更多
登录 后发表回答