Saturday, June 1, 2013

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.