The easiest way to write NSData to a file

NSData *data; data = [self fillInSomeStrangeBytes]; 

Now my question is how can I write this data the easiest way for a file.

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

+61
file file-io cocoa save
Mar 24 '09 at 20:26
source share
3 answers

NSData has a method called writeToURL:atomically: that does exactly what you want to do. See the documentation for NSData to find out how to use it.

+94
Mar 24 '09 at 20:30
source share

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

+30
Mar 24 '09 at 20:31
source share

Note that writing NSData to a file is an I / O operation that can block the main thread. Especially if the data object is large.

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

 // Use GCD 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]; }); 
+28
May 26 '14 at 6:09
source share



All Articles