将NSData写入文件的最简单方法

时间:2009-03-24 20:26:09

标签: file cocoa file-io save

NSData *data;
data = [self fillInSomeStrangeBytes];

现在我的问题是如何以最简单的方式写一个文件data

(我已经有了NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes

4 个答案:

答案 0 :(得分:98)

NSData有一个名为writeToURL:atomically:的方法,可以完全按照您的要求执行操作。查看the documentation for NSData以了解如何使用它。

答案 1 :(得分:31)

请注意,将NSData写入文件是一个IO操作,可能会阻塞主线程。特别是如果数据对象很大。

因此建议在后台线程上执行此操作,最简单的方法是使用GCD,如下所示:

// 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];
});

答案 2 :(得分:30)

如果您有文件名而不是网址,请

writeToURL:atomically:writeToFile:atomically:

答案 3 :(得分:1)

您还可以writeToFile:options:error:writeToURL:options:error:报告错误代码,以防NSData因任何原因导致保存失败。例如:

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;
}