The easiest way to write NSData to a file

FileCocoaFile IoSave

File Problem Overview


NSData *data;
data = [self fillInSomeStrangeBytes];

My question is now how I can write this data on the easiest way to an file.

(I've already an NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes)

File Solutions


Solution 1 - File

NSData has a method called writeToURL:atomically: that does exactly what you want to do. Look in the documentation for NSData to see how to use it.

Solution 2 - File

Notice that writing NSData into a file is an IO operation that may block the main thread. Especially if the data object is large.

Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:

// Use GCD's background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // Generate the file path
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.dat"];

     // Save it into file system
    [data writeToFile:dataPath atomically:YES];
});

Solution 3 - File

writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.

Solution 4 - File

You also have writeToFile:options:error: or writeToURL:options:error: which can report error codes in case the saving of the NSData failed for any reason. For example:

NSError *error;

NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
if (!folder) {
    NSLog(@"%s: %@", __FUNCTION__, error);        // handle error however you would like
    return;
}

NSURL *fileURL = [folder URLByAppendingPathComponent:filename];
BOOL success = [data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (!success) {
    NSLog(@"%s: %@", __FUNCTION__, error);        // handle error however you would like
    return;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpaprView Question on Stackoverflow
Solution 1 - FileAlexView Answer on Stackoverflow
Solution 2 - FileTom SuselView Answer on Stackoverflow
Solution 3 - FileBrian CampbellView Answer on Stackoverflow
Solution 4 - FileRobView Answer on Stackoverflow