Saturday, June 1, 2013

NSData NSDataReadingMappedIfSafe example in Objective C (iOS).

NSData NSDataReadingMappedIfSafe

Options for methods used to read NSData objects.

enum {
NSDataReadingMappedIfSafe = 1UL << 0,
NSDataReadingUncached = 1UL << 1,
NSDataReadingMappedAlways = 1UL << 3,
typedef NSUInteger NSDataReadingOptions;
A hint indicating the file should be mapped into virtual memory, if possible and safe.
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.
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...

// 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

    // 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

NSString *data = [[[NSString alloc]
                   initWithBytesNoCopy:(void *)buf.bytes
                   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.