Showing posts with label NSData example. Show all posts
Showing posts with label NSData example. Show all posts

Saturday, June 1, 2013

NSData NSDataWritingFileProtectionComplete example in Objective C (iOS).


NSData NSDataWritingFileProtectionComplete

NSDataWritingOptions
Options for methods used to write NSData objects.

enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.

NSData NSDataWritingFileProtectionComplete example.
NSData * data = // Your decrypted file data.
NSString * fileName = // Whatever you want to name your file.
NSString * path = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSURL * url = [NSURL URLWithString:path];
NSError * error = nil;

BOOL success = [data writeToURL:url
                        options:NSDataWritingFileProtectionComplete
                          error:&error];
if (success) {
    // Give the URL to Quick Look.
}
else {
    // An error happened. See the 'error' object for the details.
}

Example of [NSData NSDataWritingFileProtectionComplete].
    NSError *error = nil;
    [fileData writeToFile:filePath options:NSDataWritingFileProtectionComplete error:&error];

    if(error != nil) {
        // Failed to write the file
        NSLog(@"Failed to write file: %@", [error description]);
    } else {
        UIAlertView *filenameAlert = [[UIAlertView alloc] initWithTitle:@"File saved" message:[NSString 
stringWithFormat:@"The file %@ has been saved", [requestedURL lastPathComponent]] delegate:self cancelButtonTitle:@"OK"
otherButtonTitles:nil];

        [filenameAlert show];
        [filenameAlert release];
    }

NSData NSDataWritingFileProtectionComplete example.
NSData *theData;
NSError *error;
[theData writeToURL:someURL
            options:NSDataWritingFileProtectionComplete
              error:&error];

End of NSData NSDataWritingFileProtectionComplete example article.

NSData NSDataWritingFileProtectionNone example in Objective C (iOS).


NSData NSDataWritingFileProtectionNone

NSDataWritingOptions
Options for methods used to write NSData objects.

enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.

NSData NSDataWritingFileProtectionNone example.
NSString *myFilePath = [[NSBundle mainBundle]
                            pathForResource:@"MyFile"
                            ofType:@"txt"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directory = [NSString stringWithFormat:@"%@/Some_Directory", [paths objectAtIndex:0]];

// Check if the directory already exists
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
    // Directory does not exist so create it
    [[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
}

NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain];

NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [myFilePath lastPathComponent]]] retain];


NSError *error = nil;
if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) {
    [data writeToFile:filePath atomically:NO];
}
[data release];
[filePath release];

Example of [NSData NSDataWritingFileProtectionNone].
if([modified wirteToFile:filePath options:NSDataWritingFileProtectionNone error:&jsonParsingError])
   NSLog(@"writing ok")
else
   NSLog(@"not ok with error :%@",jsonParsinError);

End of NSData NSDataWritingFileProtectionNone example article.

NSData NSDataWritingAtomic example in Objective C (iOS).


NSData NSDataWritingAtomic

NSDataWritingOptions
Options for methods used to write NSData objects.

enum {
NSDataWritingAtomic = 1UL << 0,
NSDataWritingWithoutOverwriting = 1UL << 1,
NSDataWritingFileProtectionNone = 0x10000000,
NSDataWritingFileProtectionComplete = 0x20000000,
NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000,
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000,
NSDataWritingFileProtectionMask = 0xf0000000,
};
typedef NSUInteger NSDataWritingOptions;
Constants
NSDataWritingAtomic
A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.
NSDataWritingWithoutOverwriting
Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.
NSDataWritingFileProtectionNone
A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.
Available in iOS 4.0 and later.
Declared in NSData.h.
NSDataWritingFileProtectionComplete
A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.
NSDataWritingFileProtectionCompleteUnlessOpen
A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.
NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication
A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.
NSDataWritingFileProtectionMask
A mask to use when determining the file protection options assigned to the data.

NSData NSDataWritingAtomic example.
if (data) {   
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

Example of [NSData NSDataWritingAtomic].
NSError *error = nil;
path=@"/Users/aryaxt/Desktop/test2.avi";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

NSData NSDataWritingAtomic example.
-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];      
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}

End of NSData NSDataWritingAtomic example article.

NSData writeToFile options error example in Objective C (iOS).


NSData writeToFile options error

Writes the bytes in the receiver to the file specified by a given path.

- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

Parameters of [NSData writeToFile options error]
path
The location to which to write the receiver's bytes.
mask
A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
errorPtr
If there is an error writing out the data, upon return contains an NSError object that describes the problem.

Return Value of [NSData writeToFile options error]
YES if the operation succeeds, otherwise NO.

NSData writeToFile options error example.
if (data) {   
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

Example of [NSData writeToFile options error].
NSError *error = nil;
path=@"/Users/aryaxt/Desktop/test2.avi";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

NSData writeToFile options error example.
-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];      
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}

End of NSData writeToFile options error example article.

NSData writeToFile example in Objective C (iOS).


NSData writeToFile

Writes the bytes in the receiver to the file specified by a given path.

- (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

Parameters of [NSData writeToFile]
path
The location to which to write the receiver's bytes.
mask
A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.
errorPtr
If there is an error writing out the data, upon return contains an NSError object that describes the problem.

Return Value of [NSData writeToFile]
YES if the operation succeeds, otherwise NO.

NSData writeToFile example.
if (data) {   
     NSString *content = [[NSString alloc]  initWithBytes:[data bytes]
                                                      length:[data length] encoding: NSUTF8StringEncoding];

    NSLog(@"%@", content); // verifies data was downloaded correctly

    NSError* error;
    [data writeToFile:storePath options:NSDataWritingAtomic error:&error];

    if(error != nil)
        NSLog(@"write error %@", error);
}

Example of [NSData writeToFile].
NSError *error = nil;
path=@"/Users/aryaxt/Desktop/test2.avi";
[data writeToFile:path options:NSDataWritingAtomic error:&error];
NSLog(@"Write returned error: %@", [error localizedDescription]);

NSData writeToFile example.
-(void)banner:(NSString *)path{
   NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);         NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"banner.png"];      
   NSError *writeError = nil;
   [imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];

   if (writeError) {
      NSLog(@"Error writing file: %@", writeError);
   }
}

End of NSData writeToFile example article.

NSData NSDataReadingMappedAlways example in Objective C (iOS).


NSData NSDataReadingMappedAlways

NSDataReadingOptions
Options for methods used to read NSData objects.

enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.

NSData NSDataReadingMappedAlways example.
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *applicationDirectory = [NSString stringWithFormat:@"%@", [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];

    NSString *filePath = [NSString stringWithFormat:@"%@%@", applicationDirectory, fileNameWithExtension];

   // NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSData *fileData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedAlways error:&error];

Example of [NSData NSDataReadingMappedAlways].
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[imageLinks objectAtIndex:0]];
NSData *tdata = [NSData dataWithContentsOfURL:url options: NSDataReadingMappedAlways error:&error];
if (error) {
    NSLog(@"%@", [error localizedDescription]);
}else {
    // no error, this one is being called within my app
    NSLog(@"Data loaded successfully");
}

NSData NSDataReadingMappedAlways example.
    NSData *videoData = [NSData dataWithContentsOfFile:video.localURL options:NSDataReadingMappedAlways error:&error];

NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               videoData, video.localURL,
                               @"video/quicktime", @"contentType",
                               video.name, @"title",
                               NSLocalizedString(@"Test http://www.apple.com", @"Facebook upload description"), @"description",
                               nil];

End of NSData NSDataReadingMappedAlways example article.

NSData NSDataReadingUncached example in Objective C (iOS).


NSData NSDataReadingUncached

NSDataReadingOptions
Options for methods used to read NSData objects.

enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.

NSData NSDataReadingUncached example.
NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:yourURL options:NSDataReadingUncached error:&error];
if (error) {
    NSLog(@"%@", [error localizedDescription]);
    [error release];
} else {
    NSLog(@"Data has loaded successfully.");
}

Example of [NSData NSDataReadingUncached].
NSError *error = nil;
NSURL *url = [NSURL URLWithString:[imageLinks objectAtIndex:0]];
NSData *tdata = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
    NSLog(@"%@", [error localizedDescription]);
}else {
    // no error, this one is being called within my app
    NSLog(@"Data loaded successfully");
}

NSData NSDataReadingUncached example.
NSError *err = nil;
NSData *data [NSData dataWithContentsOfFile:path
                                    options:NSDataReadingUncached
                                      error:&err];
UIImage *img = [UIImage imageWithData:data];

End of NSData NSDataReadingUncached example article.

NSData NSDataReadingMappedIfSafe example in Objective C (iOS).


NSData NSDataReadingMappedIfSafe

NSDataReadingOptions
Options for methods used to read NSData objects.

enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
};
typedef NSUInteger NSDataReadingOptions;
Constants
NSDataReadingMappedIfSafe
A hint indicating the file should be mapped into virtual memory, if possible and safe.
NSDataReadingUncached
A hint indicating the file should not be stored in the file-system caches.
For data being read once and discarded, this option can improve performance.
NSDataReadingMappedAlways
Hint to map the file in if possible.
This takes precedence over NSDataReadingMappedIfSafe if both are given.

NSData NSDataReadingMappedIfSafe example.
// map the file, rather than loading it
NSData *data = [NSData dataWithContentsOfFile:...whatever...
                         options:NSDataReadingMappedIfSafe
                         error:&youdDoSomethingSafeHere];

// we'll maintain a read pointer to our current location in the data
NSUinteger readPointer = 0;

// continue while data remains
while(readPointer < [data length])
{
    // work out how many bytes are remaining
    NSUInteger distanceToEndOfData = [data length] - readPointer;

    // grab at most 16kb of them, being careful not to read too many
    NSString *newPortion =
         [[NSString alloc] initWithBytes:(uint8_t *)[data bytes] + readPointer
                 length:distanceToEndOfData > 16384 ? 16384 : distanceToEndOfData
                 encoding:NSUTF8StringEncoding];

    // do whatever we want with the string
    [self doSomethingWithFragment:newPortion];

    // advance our read pointer by the number of bytes actually read, and
    // clean up
    readPointer += [newPortion lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
    [newPortion release];
}

Example of [NSData NSDataReadingMappedIfSafe].
    NSData *buf = [NSData dataWithContentsOfFile:path
                                      options:NSDataReadingMappedIfSafe
                                        error:nil];

NSString *data = [[[NSString alloc]
                   initWithBytesNoCopy:(void *)buf.bytes
                   length:buf.length
                   encoding:NSUTF8StringEncoding
                   freeWhenDone:NO] autorelease];

NSData NSDataReadingMappedIfSafe example.
NSError *error;
NSData *fileData = [NSData dataWithContentsOfFile:tempFile options:NSDataReadingMappedIfSafe error:&error];
if (!fileData) {
    NSLog(@"Error %@ %@", error, [error description]);
    NSLog(@"%@", tempFile);
    //do what you need with the error
}

End of NSData NSDataReadingMappedIfSafe example article.

NSData subdataWithRange example in Objective C (iOS).


NSData subdataWithRange

Returns a data object containing the receiver’s bytes that fall within the limits specified by a given range.

- (NSData *)subdataWithRange:(NSRange)range

Parameters
range
The range in the receiver from which to get the data. The range must not exceed the bounds of the receiver.

Return Value of [NSData subdataWithRange]
A data object containing the receiver’s bytes that fall within the limits specified by range. If range isn’t within the receiver’s range of bytes, raises NSRangeException.

Discussion of [NSData subdataWithRange]
A sample using this method can be found in “Working With Binary Data”.

NSData subdataWithRange example.
while([outData length] + ptr[currentPacket].mDataByteSize < inBytesToGet && currentPacket < packetsCount)
{
NSLog(@" ++> %d", [aData retainCount]) ;
NSInteger sO = ptr[currentPacket].mStartOffset ;
NSInteger dS = ptr[currentPacket].mDataByteSize ;
NSLog(@"     get: cP: %d tP: %d mStartOffset: %d mDataByteSize: %d", currentPacket, packetsCount, sO, dS) ;
NSData *copyRange = [aData subdataWithRange: NSMakeRange(sO,dS)] ;
NSLog(@" => %d", [aData retainCount]) ;
[outData appendData:copyRange] ;
ptr[currentPacket].mStartOffset = bytesFilled + inOffset ;
[outPackets appendBytes: &ptr[currentPacket] length: sizeof(AudioStreamPacketDescription)] ;
currentPacket++ ;
bytesFilled += dS ;
}

Example of [NSData subdataWithRange].
// original data in myData
NSData *d1 = [myData subdataWithRange:NSMakeRange(0, 20)];
NSData *d2 = [myData subdataWithRange:NSMakeRange(20, 80)];

NSData subdataWithRange example.
    // Stick our chunk in the clipboard

    NSMutableArray *items = [NSMutableArray arrayWithCapacity:1];
    NSRange curRange;

    curRange.location = 0;
    curRange.length = sz;
    NSData *subData = [dataFile subdataWithRange:curRange];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:subData
forKey:(NSString *)kUTTypeAudio];
    [items addObject:dict];

End of NSData subdataWithRange example article.

NSData rangeOfData options range example in Objective C (iOS).


NSData rangeOfData options range

Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options.

- (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange

Parameters of [NSData rangeOfData options range]
dataToFind
The data for which to search. This value must not be nil.
Important: Raises an NSInvalidArgumentException if dataToFind is nil.
mask
A mask specifying search options. The “NSDataSearchOptions” options may be specified singly or by combining them with the C bitwise OR operator.
searchRange
The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException raised.

Return Value of [NSData rangeOfData options range]
An NSRange structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@"").

NSData rangeOfData options range example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
                                       length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
                                       length:3];

NSRange range = [data1 rangeOfData:data2
                           options:0
                             range:NSMakeRange(0, [data1 length])];

if(range.location != NSNotFound)
{
     NSLog(@"Found pattern!");
}

Example of [NSData rangeOfData options range].
    NSString *testString = @"01K234567K";
    NSData *testData = [testString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *testLetter = @"K";
    NSData *kData = [testLetter dataUsingEncoding:NSUTF8StringEncoding];
    NSRange whereisK = [testData rangeOfData:kData options:NSDataSearchBackwards      range:NSMakeRange(0, [testData length])];
    NSLog(@"loc: %d, len: %d",whereisK.location,whereisK.length);

NSData rangeOfData options range example.
const NSUInteger dataLength = 130;
unsigned char dataBytes[dataLength] = {
0x01,0x00,0x00,0x04,0x40,0x00,0x00,0x00,0x00,0x41,0x41,0x41,0x41,0x48,0x47,0x5A,
0x30,0x65,0x58,0x42,0x4E,0x4E,0x45,0x45,0x67,0x41,0x41,0x41,0x41,0x41,0x45,0x30,
0x30,0x51,0x53,0x42,0x74,0x63,0x44,0x51,0x79,0x61,0x58,0x4E,0x76,0x62,0x51,0x41,
0x41,0x41,0x2B,0x39,0x74,0x62,0x32,0x39,0x32,0x41,0x41,0x41,0x41,0x62,0x47,0x31,
0x32,0x61,0x47,0x51,0x41,0x41,0x41,0x41,0x41,0x71,0x67,0x59,0x35,0x79,0x36,0x6F,
0x47,0x4F,0x63,0x73,0x41,0x41,0x4B,0x78,0x45,0x41,0x41,0x43,0x34,0x41,0x41,0x41,
0x42,0x41,0x41,0x41,0x42,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41,0x41,0x41,0x41,0x41,0x51,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41};
NSData *data = [NSData dataWithBytes:dataBytes length:130];

const NSUInteger startBytesLength = 4;
unsigned char startBytes[startBytesLength] = {0x40, 0x00, 0x00, 0x00};
const NSUInteger stopBytesLength = 1;
unsigned char stopBytes[stopBytesLength] = {0x34};

NSData *startData = [NSData dataWithBytes:startBytes length:startBytesLength];
NSData *stopData  = [NSData dataWithBytes:stopBytes  length:stopBytesLength];
NSRange startRange = [data rangeOfData:startData options:0 range:NSMakeRange(0, dataLength)];
NSUInteger start = startRange.location;

NSRange stopRange  = [data rangeOfData:stopData  options:0 range:NSMakeRange(start+startBytesLength, dataLength-(start+startBytesLength))];
NSUInteger length = stopRange.location - start;
NSUInteger stopLocation = stopRange.location+stopBytesLength;

NSData *extractData = [data subdataWithRange:NSMakeRange(start, length)];
NSLog(@"extractData: %@", extractData);

NSMutableData *newData = [NSMutableData data];
[newData appendData:[data subdataWithRange:NSMakeRange(0, start)]];
[newData appendData:[data subdataWithRange:NSMakeRange(stopLocation, dataLength-stopLocation)]];
NSLog(@"newData: %@", newData);

End of NSData rangeOfData options range example article.

NSData rangeOfData example in Objective C (iOS).


NSData rangeOfData

Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options.

- (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange

Parameters of [NSData rangeOfData]
dataToFind
The data for which to search. This value must not be nil.
Important: Raises an NSInvalidArgumentException if dataToFind is nil.
mask
A mask specifying search options. The “NSDataSearchOptions” options may be specified singly or by combining them with the C bitwise OR operator.
searchRange
The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException raised.

Return Value of [NSData rangeOfData]
An NSRange structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@"").

NSData rangeOfData example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
                                       length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
                                       length:3];

NSRange range = [data1 rangeOfData:data2
                           options:0
                             range:NSMakeRange(0, [data1 length])];

if(range.location != NSNotFound)
{
     NSLog(@"Found pattern!");
}

Example of [NSData rangeOfData].
    NSString *testString = @"01K234567K";
    NSData *testData = [testString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *testLetter = @"K";
    NSData *kData = [testLetter dataUsingEncoding:NSUTF8StringEncoding];
    NSRange whereisK = [testData rangeOfData:kData options:NSDataSearchBackwards      range:NSMakeRange(0, [testData length])];
    NSLog(@"loc: %d, len: %d",whereisK.location,whereisK.length);

NSData rangeOfData example.
const NSUInteger dataLength = 130;
unsigned char dataBytes[dataLength] = {
0x01,0x00,0x00,0x04,0x40,0x00,0x00,0x00,0x00,0x41,0x41,0x41,0x41,0x48,0x47,0x5A,
0x30,0x65,0x58,0x42,0x4E,0x4E,0x45,0x45,0x67,0x41,0x41,0x41,0x41,0x41,0x45,0x30,
0x30,0x51,0x53,0x42,0x74,0x63,0x44,0x51,0x79,0x61,0x58,0x4E,0x76,0x62,0x51,0x41,
0x41,0x41,0x2B,0x39,0x74,0x62,0x32,0x39,0x32,0x41,0x41,0x41,0x41,0x62,0x47,0x31,
0x32,0x61,0x47,0x51,0x41,0x41,0x41,0x41,0x41,0x71,0x67,0x59,0x35,0x79,0x36,0x6F,
0x47,0x4F,0x63,0x73,0x41,0x41,0x4B,0x78,0x45,0x41,0x41,0x43,0x34,0x41,0x41,0x41,
0x42,0x41,0x41,0x41,0x42,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41,0x41,0x41,0x41,0x41,0x51,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x41,
0x41,0x41};
NSData *data = [NSData dataWithBytes:dataBytes length:130];

const NSUInteger startBytesLength = 4;
unsigned char startBytes[startBytesLength] = {0x40, 0x00, 0x00, 0x00};
const NSUInteger stopBytesLength = 1;
unsigned char stopBytes[stopBytesLength] = {0x34};

NSData *startData = [NSData dataWithBytes:startBytes length:startBytesLength];
NSData *stopData  = [NSData dataWithBytes:stopBytes  length:stopBytesLength];
NSRange startRange = [data rangeOfData:startData options:0 range:NSMakeRange(0, dataLength)];
NSUInteger start = startRange.location;

NSRange stopRange  = [data rangeOfData:stopData  options:0 range:NSMakeRange(start+startBytesLength, dataLength-(start+startBytesLength))];
NSUInteger length = stopRange.location - start;
NSUInteger stopLocation = stopRange.location+stopBytesLength;

NSData *extractData = [data subdataWithRange:NSMakeRange(start, length)];
NSLog(@"extractData: %@", extractData);

NSMutableData *newData = [NSMutableData data];
[newData appendData:[data subdataWithRange:NSMakeRange(0, start)]];
[newData appendData:[data subdataWithRange:NSMakeRange(stopLocation, dataLength-stopLocation)]];
NSLog(@"newData: %@", newData);

End of NSData rangeOfData example article.

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.

NSData initWithData example in Objective C (iOS).


NSData initWithData

Returns a data object initialized with the contents of another data object.

- (id)initWithData:(NSData *)data

Parameters
data
A data object.

Return Value of [NSData initWithData]
A data object initialized with the contents data. The returned object might be different than the original receiver.

NSData initWithData example.
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"Pacific_Map" ofType:@"png"];
NSURL* urlEx = [NSURL fileURLWithPath:imagePath];
NSData* mapExIMGData = [[NSData alloc] initWithContentsOfURL: urlEx];

UIImage* imgEx = [[UIImage alloc] initWithData:mapExIMGData];

mapImageViewEx.image = imgEx;

End of NSData initWithData example article.

NSData initWithContentsOfFile options error example in Objective C (iOS).


NSData initWithContentsOfFile options error

Returns a data object initialized by reading into it the data from the file specified by a given path.

- (id)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

Parameters of [NSData initWithContentsOfFile options error]
path
The absolute path of the file from which to read data.
mask
A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.
errorPtr
If an error occurs, upon return contains an NSError object that describes the problem.

Return Value of [NSData initWithContentsOfFile options error]
A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.

NSData initWithContentsOfFile options error example.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createEditableCopyOfDatabaseIfNeeded];

    NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"testList.plist"];

    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data == nil) {
    NSLog(@"yes nil");
}
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];

}

Example of [NSData initWithContentsOfFile options error].
-(FileHash*) hashFileByName :(NSString*) filePath{

    NSAutoreleasePool *innerpool = [[NSAutoreleasePool alloc]init];

    //NSData* inputData = [inputStr dataUsingEncoding:NSUTF8StringEncoding];
    NSData* inputData = [[[NSData alloc]initWithContentsOfFile:filePath] autorelease];
    unsigned char outputData[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512([inputData bytes], [inputData length], outputData);

    NSMutableString* hashStr = [NSMutableString string];
    int i = 0;
    for (i = 0; i < CC_SHA512_DIGEST_LENGTH; ++i)
     [hashStr appendFormat:@"%02x", outputData[i]];


    [innerpool drain];

    //NSLog(@"%@ hash : %@",filePath,hashStr);

    FileHash *hash = [[[FileHash alloc]init]autorelease];
    [hash setFileHash:hashStr];
    [hash setFilePath:filePath];

    return hash;
}

NSData initWithContentsOfFile options error example.
- (UIImage *)imageFromDiskForURL:(NSString *)url
{
    NSData *data = [[NSData alloc] initWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
    UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
    [data release];
    return i;
}

End of NSData initWithContentsOfFile options error example article.

NSData initWithContentsOfFile example in Objective C (iOS).


NSData initWithContentsOfFile

Returns a data object initialized by reading into it the data from the file specified by a given path.

- (id)initWithContentsOfFile:(NSString *)path

Parameters
path
The absolute path of the file from which to read data.

Return Value
A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.

Discussion of [NSData initWithContentsOfFile]
This method is equivalent to initWithContentsOfFile:options:error: with no options.

NSData initWithContentsOfFile example.
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self createEditableCopyOfDatabaseIfNeeded];

    NSString *path = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"testList.plist"];

    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
if (data == nil) {
    NSLog(@"yes nil");
}
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    parser.delegate = self;
    [parser parse];

}

Example of [NSData initWithContentsOfFile].
-(FileHash*) hashFileByName :(NSString*) filePath{

    NSAutoreleasePool *innerpool = [[NSAutoreleasePool alloc]init];

    //NSData* inputData = [inputStr dataUsingEncoding:NSUTF8StringEncoding];
    NSData* inputData = [[[NSData alloc]initWithContentsOfFile:filePath] autorelease];
    unsigned char outputData[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512([inputData bytes], [inputData length], outputData);

    NSMutableString* hashStr = [NSMutableString string];
    int i = 0;
    for (i = 0; i < CC_SHA512_DIGEST_LENGTH; ++i)
     [hashStr appendFormat:@"%02x", outputData[i]];


    [innerpool drain];

    //NSLog(@"%@ hash : %@",filePath,hashStr);

    FileHash *hash = [[[FileHash alloc]init]autorelease];
    [hash setFileHash:hashStr];
    [hash setFilePath:filePath];

    return hash;
}

NSData initWithContentsOfFile example.
- (UIImage *)imageFromDiskForURL:(NSString *)url
{
    NSData *data = [[NSData alloc] initWithContentsOfFile:cachePathForURL(url) options:0 error:NULL];
    UIImage *i = [[[UIImage alloc] initWithData:data] autorelease];
    [data release];
    return i;
}

End of NSData initWithContentsOfFile example article.

NSData initWithBytesNoCopy length example in Objective C (iOS).


NSData initWithBytesNoCopy length

Returns a data object initialized by adding to it a given number of bytes of data from a given buffer.

- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data for the new object. bytes must point to a memory block allocated with malloc.
length
The number of bytes to hold from bytes. This value must not exceed the length of bytes.

Return Value of [NSData initWithBytesNoCopy length]
A data object initialized by adding to it length bytes of data from the buffer bytes. The returned object might be different than the original receiver.

Discussion of [NSData initWithBytesNoCopy length]
The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.

NSData initWithBytesNoCopy length example.
int offset = 10;
NSRange dataRange;
dataRange.length = [data length] - offset;
dataRange.location = offset;

void *buffer = malloc(dataRange.length);
[data getBytes:buffer range:dataRange];
self.bodyData = [[NSData alloc] initWithBytesNoCopy:buffer length:dataRange.length];
free(buffer); //Make sure your property has either retain attribute (or strong if using ARC)

Example of [NSData initWithBytesNoCopy length].
if (flags == nil) {
   flagPtr *flgH = &flags;
   NSData *flgsDatum =
      [[NSData alloc] initWithBytesNoCopy:flgH length:sizeof(flgH)
freeWhenDone:NO];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"fetchFlags"
object:flgsDatum];
   *flags = (WORKING | (*flags & LOGFILE));
}

NSData initWithBytesNoCopy length example.
- (NSString *)hashWithDigest:(AUMessageDigest)digest data:(NSData **)data
{
    u_byte *(*CC_XXX)(const void *, CC_LONG, u_byte *);
    CC_LONG CC_XXX_DIGEST_LEN;
    u_byte *md = NULL;
    NSInteger i = 0;
    NSString *result;
    NSMutableString *buffer;
   
    switch (digest) {
        case AUDigestSHA1:
            CC_XXX = CC_SHA1;
            CC_XXX_DIGEST_LEN = CC_SHA1_DIGEST_LENGTH;
        break;
        case AUDigestSHA256:
            CC_XXX = CC_SHA256;
            CC_XXX_DIGEST_LEN = CC_SHA256_DIGEST_LENGTH;
        break;
        case AUDigestSHA512:
            CC_XXX = CC_SHA512;
            CC_XXX_DIGEST_LEN = CC_SHA512_DIGEST_LENGTH;
        break;
        case AUDigestMD5:
            CC_XXX = CC_MD5;
            CC_XXX_DIGEST_LEN = CC_MD5_DIGEST_LENGTH;
        break;
        default:
            return nil;
    }
   
    result = nil;
    if((md = malloc(CC_XXX_DIGEST_LEN * sizeof(u_byte) + 1))) {
        memset(md, 0, CC_XXX_DIGEST_LEN + 1);
        CC_XXX([self bytes], [self length], md);
        buffer = [NSMutableString string];
        for (i = 0; i< CC_XXX_DIGEST_LEN; i++) {
            [buffer appendFormat:@"%02x", (CC_LONG)(md[i])];
        }
        if (data != nil) {
            *data = [[NSData alloc] initWithBytesNoCopy:md length:CC_XXX_DIGEST_LEN freeWhenDone:YES];
        } else {
            free(md);
        }
        result = [NSString stringWithString:buffer];
    }
    return result;
}

End of NSData initWithBytesNoCopy length example article.

NSData initWithBytesNoCopy example in Objective C (iOS).


NSData initWithBytesNoCopy

Returns a data object initialized by adding to it a given number of bytes of data from a given buffer.

- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length

Parameters of [NSData initWithBytesNoCopy]
bytes
A buffer containing data for the new object. bytes must point to a memory block allocated with malloc.
length
The number of bytes to hold from bytes. This value must not exceed the length of bytes.

Return Value
A data object initialized by adding to it length bytes of data from the buffer bytes. The returned object might be different than the original receiver.

Discussion of [NSData initWithBytesNoCopy]
The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.

NSData initWithBytesNoCopy example.
int offset = 10;
NSRange dataRange;
dataRange.length = [data length] - offset;
dataRange.location = offset;

void *buffer = malloc(dataRange.length);
[data getBytes:buffer range:dataRange];
self.bodyData = [[NSData alloc] initWithBytesNoCopy:buffer length:dataRange.length];
free(buffer); //Make sure your property has either retain attribute (or strong if using ARC)

Example of [NSData initWithBytesNoCopy].
if (flags == nil) {
   flagPtr *flgH = &flags;
   NSData *flgsDatum =
      [[NSData alloc] initWithBytesNoCopy:flgH length:sizeof(flgH)
freeWhenDone:NO];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"fetchFlags"
object:flgsDatum];
   *flags = (WORKING | (*flags & LOGFILE));
}

NSData initWithBytesNoCopy example.
- (NSString *)hashWithDigest:(AUMessageDigest)digest data:(NSData **)data
{
    u_byte *(*CC_XXX)(const void *, CC_LONG, u_byte *);
    CC_LONG CC_XXX_DIGEST_LEN;
    u_byte *md = NULL;
    NSInteger i = 0;
    NSString *result;
    NSMutableString *buffer;
   
    switch (digest) {
        case AUDigestSHA1:
            CC_XXX = CC_SHA1;
            CC_XXX_DIGEST_LEN = CC_SHA1_DIGEST_LENGTH;
        break;
        case AUDigestSHA256:
            CC_XXX = CC_SHA256;
            CC_XXX_DIGEST_LEN = CC_SHA256_DIGEST_LENGTH;
        break;
        case AUDigestSHA512:
            CC_XXX = CC_SHA512;
            CC_XXX_DIGEST_LEN = CC_SHA512_DIGEST_LENGTH;
        break;
        case AUDigestMD5:
            CC_XXX = CC_MD5;
            CC_XXX_DIGEST_LEN = CC_MD5_DIGEST_LENGTH;
        break;
        default:
            return nil;
    }
   
    result = nil;
    if((md = malloc(CC_XXX_DIGEST_LEN * sizeof(u_byte) + 1))) {
        memset(md, 0, CC_XXX_DIGEST_LEN + 1);
        CC_XXX([self bytes], [self length], md);
        buffer = [NSMutableString string];
        for (i = 0; i< CC_XXX_DIGEST_LEN; i++) {
            [buffer appendFormat:@"%02x", (CC_LONG)(md[i])];
        }
        if (data != nil) {
            *data = [[NSData alloc] initWithBytesNoCopy:md length:CC_XXX_DIGEST_LEN freeWhenDone:YES];
        } else {
            free(md);
        }
        result = [NSString stringWithString:buffer];
    }
    return result;
}

End of NSData initWithBytesNoCopy example article.

NSData initWithBytes length example in Objective C (iOS).


NSData initWithBytes length

Returns a data object initialized by adding to it a given number of bytes of data copied from a given buffer.

- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length

Discussion of [NSData initWithBytes length]
A data object initialized by adding to it length bytes of data copied from the buffer bytes. The returned object might be different than the original receiver.

NSData initWithBytes length example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
                                       length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
                                       length:3];

NSRange range = [data1 rangeOfData:data2
                           options:0
                             range:NSMakeRange(0, [data1 length])];

if(range.location != NSNotFound)
{
     NSLog(@"Found pattern!");
}

Example of [NSData initWithBytes length].
cat.catName = (catName)?[NSString stringWithUTF8String:catName]:@"";
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 2) length: sqlite3_column_bytes(statement, 2)];          
cat.catThumb = [UIImage imageWithData:dataForCachedImage];
[dataForCachedImage release];

NSData initWithBytes length example.
Here's how I've done that before:

UInt8 j= 0x0f;
NSData *data = [[[NSData alloc] initWithBytes:&j length:sizeof(j)] autorelease];

End of NSData initWithBytes length example article.

NSData initWithBytes example in Objective C (iOS).


NSData initWithBytes

Returns a data object initialized by adding to it a given number of bytes of data copied from a given buffer.

- (id)initWithBytes:(const void *)bytes length:(NSUInteger)length

Discussion of [NSData initWithBytes]
A data object initialized by adding to it length bytes of data copied from the buffer bytes. The returned object might be different than the original receiver.

NSData initWithBytes example.
//This is just mock up data to represent what would be passed into your method
unsigned char ch1[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x04, 0x01, 0x00, 0x0F };
NSData *data1 = [[NSData alloc] initWithBytes:ch1
                                       length:sizeof(ch1)];
//This is the data used for the comparison
NSData *data2 = [[NSData alloc] initWithBytes:(unsigned char[]){0x04, 0x01, 0x00}
                                       length:3];

NSRange range = [data1 rangeOfData:data2
                           options:0
                             range:NSMakeRange(0, [data1 length])];

if(range.location != NSNotFound)
{
     NSLog(@"Found pattern!");
}

Example of [NSData initWithBytes].
cat.catName = (catName)?[NSString stringWithUTF8String:catName]:@"";
NSData *dataForCachedImage = [[NSData alloc] initWithBytes:sqlite3_column_blob(statement, 2) length: sqlite3_column_bytes(statement, 2)];          
cat.catThumb = [UIImage imageWithData:dataForCachedImage];
[dataForCachedImage release];

NSData initWithBytes example.
Here's how I've done that before:

UInt8 j= 0x0f;
NSData *data = [[[NSData alloc] initWithBytes:&j length:sizeof(j)] autorelease];

End of NSData initWithBytes example article.

NSData getBytes range example in Objective C (iOS).


NSData getBytes range

Copies a range of bytes from the receiver’s data into a given buffer.

- (void)getBytes:(void *)buffer range:(NSRange)range

Parameters of [NSData getBytes range]
buffer
A buffer into which to copy data.
range
The range of bytes in the receiver's data to copy to buffer. The range must lie within the range of bytes of the receiver's data.

Discussion of [NSData getBytes range]
If range isn’t within the receiver’s range of bytes, an NSRangeException is raised.

NSData getBytes range example.
NSData *data = ...;
NSMutableArray *bytes = [NSMutableArray array];
for (NSUInteger i = 0; i < [data length]; i++) {
    unsigned char byte;
    [data getBytes:&byte range:NSMakeRange(i, 1)];
    [bytes addObject:[NSString stringWithFormat:@"%x", byte]];
}
NSLog(@"%@", bytes);

Example of [NSData getBytes range].
- (NSData *)getSubData:(NSData *)source withRange:(NSRange)range
{
    UInt8 bytes[range.length];
    [source getBytes:&bytes range:range];
    NSData *result = [[NSData alloc] initWithBytes:bytes length:sizeof(bytes)];
    return [result autorelease];
}

NSData getBytes range example.
UInt16 anUInt16;
float aFloat;

int position = 0;

[data getBytes:&anUInt16 range:NSMakeRange(position, sizeof(UInt16))];
position += sizeof(UInt16);

[data getBytes:&aFloat range:NSMakeRange(position, sizeof(float))];
position += sizeof(float);

End of NSData getBytes range example article.