The easiest way to write NSData to a file

前端 未结 4 439
悲哀的现实
悲哀的现实 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;
    }
    

提交回复
热议问题