Saturday, June 1, 2013

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.