The easiest way to write NSData to a file

前端 未结 4 432
悲哀的现实
悲哀的现实 2020-12-05 01:36
NSData *data;
data = [self fillInSomeStrangeBytes];

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

相关标签:
4条回答
  • 2020-12-05 02:00

    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;
    }
    
    0 讨论(0)
  • 2020-12-05 02:04

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

    0 讨论(0)
  • 2020-12-05 02:05

    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];
    });
    
    0 讨论(0)
  • 2020-12-05 02:07

    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.

    0 讨论(0)
提交回复
热议问题