Saturday, June 1, 2013

NSData isEqualToData example in Objective C (iOS).


NSData isEqualToData

Compares the receiving data object to otherData.

- (BOOL)isEqualToData:(NSData *)otherData

Parameters
otherData
The data object with which to compare the receiver.

Return Value
YES if the contents of otherData are equal to the contents of the receiver, otherwise NO.

Discussion of [NSData isEqualToData]
Two data objects are equal if they hold the same number of bytes, and if the bytes at the same position in the objects are the same.

NSData isEqualToData example.
-(BOOL)checkHeader{
char tmp[3];
[receivedStream getBytes:&tmp length:3];
NSData *temp = [NSData dataWithBytes:tmp length:3];
NSData *tmp2 = [NSData dataWithBytes:header length:3];
BOOL test = [tmp2 isEqualToData:temp];
    return test;
}

Example of [NSData isEqualToData].
if (![filename isEqualToString:@""]) //this makes sure we did not submitted upload form without selecting file
{
UInt16 separatorBytes = 0x0A0D;
NSMutableData* separatorData = [NSMutableData dataWithBytes:&separatorBytes length:2];
[separatorData appendData:[multipartData objectAtIndex:0]];
int l = [separatorData length];
int count = 2; //number of times the separator shows up at the end of file data

NSFileHandle* dataToTrim = [multipartData lastObject];
NSLog(@"data: %@", dataToTrim);

for (unsigned long long i = [dataToTrim offsetInFile] - l; i > 0; i--)
{
[dataToTrim seekToFileOffset:i];
if ([[dataToTrim readDataOfLength:l] isEqualToData:separatorData])
{
[dataToTrim truncateFileAtOffset:i];
i -= l;
if (--count == 0) break;
}
}

NSLog(@"NewFileUploaded");
[[NSNotificationCenter defaultCenter] postNotificationName:@"NewFileUploaded" object:nil];
}

NSData isEqualToData example.
NSData *webData= [NSData dataWithContentsOfURL:webPath]; //retrieve from web
UIImage *webImage = [UIImage imageWithData:webData]; //works fine

[webData writeToURL:filePath atomically:YES]; //cache
NSData *cacheData = [NSData dataWithContentsOfURL:filePath];
if ([cacheData isEqualToData:webData]) NSLog(@"Equal");
UIImage *cacheImage = [UIImage imageWithData:cacheData]; 

End of NSData isEqualToData example article.