Saturday, June 1, 2013

NSMutableData initWithLength example in Objective C (iOS).


NSMutableData initWithLength

Initializes and returns an NSMutableData object containing a given number of zeroed bytes.

- (id)initWithLength:(NSUInteger)length

Parameters
length
The number of bytes the object initially contains.

Return Value of [NSMutableData initWithLength]
An initialized NSMutableData object containing length zeroed bytes.

NSMutableData initWithLength example.
-(NSMutableData*) bar
{
    return [[[NSMutableData alloc] initWithLength:100] autorelease];
}

Example of [NSMutableData initWithLength].
 NSUInteger length = [[invocation methodSignature] methodReturnLength];
if(length!=0){
    NSMutableData * dat = [[NSMutableData alloc] initWithLength:length];
    void* returnBuffer =  [dat mutableBytes];
    [invocation getReturnValue:&returnBuffer];
    void(^delayedFree)(void) = ^{ [dat release]; };
    [[NSOperationQueue mainQueue] addOperationWithBlock:delayedFree];
    return returnBuffer;
}
return nil;

NSMutableData initWithLength example.
- (NSMutableData *)dataToBeLoaded;
{
    if (!_dataToBeLoaded) {
        _dataToBeLoaded = [[NSMutableData alloc] initWithLength:1000];
    }
    return _dataToBeLoaded;
}

End of NSMutableData initWithLength example article.

NSMutableData initWithCapacity example in Objective C (iOS).


NSMutableData initWithCapacity

Returns an initialized NSMutableData object capable of holding the specified number of bytes.

- (id)initWithCapacity:(NSUInteger)capacity

Parameters
capacity
The number of bytes the data object can initially contain.

Return Value
An initialized NSMutableData object capable of holding capacity bytes.

Discussion of [NSMutableData initWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.

If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.

NSMutableData initWithCapacity example.
self.receiveData = [[[NSMutableData alloc] initWithCapacity:0] autorelease];
OR

 NSMutableData * myData =  [[NSMutableData alloc] initWithCapacity:0];
   self.receiveData = myData ;
   [myData release];
    myData  = nil ;

Example of [NSMutableData initWithCapacity].

-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {

    if (data==nil) {

        data = [[NSMutableData alloc] initWithCapacity:2048];

    }

    [data appendData:incrementalData];

}

NSMutableData initWithCapacity example.
-(void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData {
    if (data==nil) { data = [[NSMutableData alloc] initWithCapacity:2048]; }
    [data appendData:incrementalData];
}

End of NSMutableData initWithCapacity example article.

NSMutableData increaseLengthBy example in Objective C (iOS).


NSMutableData increaseLengthBy

Increases the length of the receiver by a given number of bytes.

- (void)increaseLengthBy:(NSUInteger)extraLength

Parameters
extraLength
The number of bytes by which to increase the receiver's length.

Discussion of [NSMutableData increaseLengthBy]
The additional bytes are all set to 0.

NSMutableData increaseLengthBy example.
ou want to use an NSMutableData, which you make from the NSData you get back from the string, then add some zeros:

NSMutableData paddedData = [NSMutableData dataWithData:d];
[paddedData increaseLengthBy:4];

Example of [NSMutableData increaseLengthBy].
NSData* compressData(NSData* uncompressedData) {
if ([uncompressedData length] == 0) return uncompressedData;

z_stream strm;

strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.total_out = 0;
strm.next_in=(Bytef *)[uncompressedData bytes];
strm.avail_in = (unsigned int)[uncompressedData length];

// Compresssion Levels:
//   Z_NO_COMPRESSION
//   Z_BEST_SPEED
//   Z_BEST_COMPRESSION
//   Z_DEFAULT_COMPRESSION

if (deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY) != Z_OK) return nil;

NSMutableData *compressed = [NSMutableData dataWithLength:16384];  // 16K chunks for expansion

do {

    if (strm.total_out >= [compressed length])
        [compressed increaseLengthBy: 16384];

    strm.next_out = [compressed mutableBytes] + strm.total_out;
    strm.avail_out = (unsigned int)([compressed length] - strm.total_out);

    deflate(&strm, Z_FINISH); 

} while (strm.avail_out == 0);

deflateEnd(&strm);

[compressed setLength: strm.total_out];
return [NSData dataWithData:compressed];
}

NSMutableData increaseLengthBy example.
if ([compressedData length] == 0) return compressedData;

NSUInteger full_length = [compressedData length];
NSUInteger half_length = [compressedData length] / 2;

NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
BOOL done = NO;
int status;

z_stream strm;
strm.next_in = (Bytef *)[compressedData bytes];
strm.avail_in = (unsigned int)[compressedData length];
strm.total_out = 0;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;

if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;

while (!done) {
    // Make sure we have enough room and reset the lengths.
    if (strm.total_out >= [decompressed length]) {
        [decompressed increaseLengthBy: half_length];
    }
    strm.next_out = [decompressed mutableBytes] + strm.total_out;
    strm.avail_out = (unsigned int)([decompressed length] - strm.total_out);

    // Inflate another chunk.
    status = inflate (&strm, Z_SYNC_FLUSH);
    if (status == Z_STREAM_END) {
        done = YES;
    } else if (status != Z_OK) {
        break;
    }
}
if (inflateEnd (&strm) != Z_OK) return nil;

// Set real length.
if (done) {
    [decompressed setLength: strm.total_out];
    return [NSData dataWithData: decompressed];
} else {
    return nil;
}
}

End of NSMutableData increaseLengthBy example article.

NSMutableData appendData example in Objective C (iOS).


NSMutableData appendData

Appends the content of another NSData object to the receiver.

- (void)appendData:(NSData *)otherData

Parameters of [NSMutableData appendData]
otherData
The data object whose content is to be appended to the contents of the receiver.

NSMutableData appendData example.
self.globalData = [[NSMutableData alloc] init];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.globalData appendData:data];
    float progress = (float)[self.globalData length] / self.downloadSize;
    self.threadProgressView.progress = progress;
}

Example of [NSMutableData appendData].
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if(!receivedData)
    {
        receivedData = [NSMutableData data];
    }
    [receivedData appendData:data];
}

NSMutableData appendData example.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
  NSMutableData *currentData = (NSMutableData*)[receivedData objectForKey:[connection description]];
  [currentData.appendData:data];
}

End of NSMutableData appendData example article.

NSMutableData appendBytes length example in Objective C (iOS).


NSMutableData appendBytes length

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes length]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes length example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes length].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes length example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes length example article.

NSMutableData appendBytes example in Objective C (iOS).


NSMutableData appendBytes

Appends to the receiver a given number of bytes from a given buffer.

- (void)appendBytes:(const void *)bytes length:(NSUInteger)length

Parameters
bytes
A buffer containing data to append to the receiver's content.
length
The number of bytes from bytes to append.

Discussion of [NSMutableData appendBytes]
A sample using this method can be found in Working With Mutable Binary Data.

NSMutableData appendBytes example.
For example, to convert from host (your machine) to network endianness, use htonl():

uint32_t theInt = htonl((uint32_t)myInteger);
[myData appendBytes:&theInt length:sizeof(theInt)];

Example of [NSMutableData appendBytes].
NSMutableData *data = [NSMutableData data];
char bytesToAppend[5] = {0x01, 0xf0, 0x64, 0x0, 0x6a};
[data appendBytes:bytesToAppend length:sizeof(bytesToAppend)];

NSMutableData appendBytes example.
To store:

SInt16 *frames = ...;
NSUInteger length = ...;    // Assuming number of elements in frames, not bytes!  
NSMutableData *data = [[NSMutableData alloc] initWithCapacity:0];
[data appendBytes:(const void *)frames length:length * sizeof(SInt16)];
To retrieve:

SInt16 *frames = (SInt16 *)[data bytes];
NSUInteger length = [data length] / sizeof(SInt16);

End of NSMutableData appendBytes example article.

NSMutableData dataWithLength example in Objective C (iOS).


NSMutableData dataWithLength

Creates and returns an NSMutableData object containing a given number of zeroed bytes.

+ (id)dataWithLength:(NSUInteger)length

Parameters
length
The number of bytes the new data object initially contains.

Return Value of [NSMutableData dataWithLength]
A new NSMutableData object of length bytes, filled with zeros.

NSMutableData dataWithLength example.
 long long length = 1024ull * 1024ull * 1024ull * 2ull; // 2 GB

 db = [NSMutableData dataWithLength:length];

 char *array = [db mutableBytes];

 for(long long i = 0; i < length - 1; i++) {
      array[i] = i % 256;
 }

Example of [NSMutableData dataWithLength].
NSMutableData* mutableData = [NSMutableData dataWithLength: someLength];
void* bitmapData = [mutableData mutableBytes];
CGContextRef context = CGBitmapContextCreate(bitmapData,...);
// ...use context
CGContextRelease(context);

NSMutableData dataWithLength example.
- (NSData *)gzipInflate:(NSData*)data
{
    if ([data length] == 0) return data;

    unsigned full_length = [data length];
    unsigned half_length = [data length] / 2;

    NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length];
    BOOL done = NO;
    int status;

    z_stream strm;
    strm.next_in = (Bytef *)[data bytes];
    strm.avail_in = [data length];
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;

    if (inflateInit2(&strm, (15+32)) != Z_OK) return nil;
    while (!done)
    {
        // Make sure we have enough room and reset the lengths.
        if (strm.total_out >= [decompressed length])
            [decompressed increaseLengthBy: half_length];
        strm.next_out = [decompressed mutableBytes] + strm.total_out;
        strm.avail_out = [decompressed length] - strm.total_out;

        // Inflate another chunk.
        status = inflate (&strm, Z_SYNC_FLUSH);
        if (status == Z_STREAM_END) done = YES;
        else if (status != Z_OK) break;
    }
    if (inflateEnd (&strm) != Z_OK) return nil;

    // Set real length.
    if (done)
    {
        [decompressed setLength: strm.total_out];
        return [NSData dataWithData: decompressed];
    }
    else return nil;
}

End of NSMutableData dataWithLength example article.

NSMutableData dataWithCapacity example in Objective C (iOS).


NSMutableData dataWithCapacity

Creates and returns an NSMutableData object capable of holding the specified number of bytes.

+ (id)dataWithCapacity:(NSUInteger)aNumItems

Parameters
aNumItems
The number of bytes the new data object can initially contain.

Return Value
A new NSMutableData object capable of holding aNumItems bytes.

Discussion of [NSMutableData dataWithCapacity]
This method doesn’t necessarily allocate the requested memory right away. Mutable data objects allocate additional memory as needed, so aNumItems simply establishes the object’s initial capacity. When it does allocate the initial memory, though, it allocates the specified amount. This method sets the length of the data object to 0.

If the capacity specified in aNumItems is greater than four memory pages in size, this method may round the amount of requested memory up to the nearest full page.

NSMutableData dataWithCapacity example.
#include 

-(NSData*)create20mbRandomNSData
{
  int twentyMb           = 20971520;
  NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
  for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
  {
    u_int32_t randomBits = arc4random();
    [theData appendBytes:(void*)&randomBits length:4];
  }
  return theData;
}

Example of [NSMutableData dataWithCapacity].
- (NSData *)randomDataWithBytes: (NSUInteger)length {
    NSMutableData *mutableData = [NSMutableData dataWithCapacity: length];
    for (unsigned int i = 0; i < size; i++) {
        NSInteger randomBits = arc4random();
        [mutableData appendBytes: (void *) &randomBits length: 1];
    } return mutableData;
}

NSMutableData dataWithCapacity example.
encoding:

NSMutableData * data = [NSMutableData dataWithCapacity:0];
float z = ...;
[data appendBytes:&z length:sizeof(float)];
decoding:

NSData * data = ...; // loaded from bluetooth
float z;
[data getBytes:&z length:sizeof(float)];

End of NSMutableData dataWithCapacity example article.

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 freeWhenDone example in Objective C (iOS).


NSData initWithBytesNoCopy length freeWhenDone

Initializes a newly allocated data object by adding to it length bytes of data from the buffer bytes.

- (id)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)flag

Parameters of [NSData initWithBytesNoCopy length freeWhenDone]
bytes
A buffer containing data for the new object. If flag is YES, 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.
flag
If YES, the returned object takes ownership of the bytes pointer and frees it on deallocation.

NSData initWithBytesNoCopy length freeWhenDone 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 freeWhenDone].
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 freeWhenDone 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 freeWhenDone example article.