writeToFile 失败,错误 = null

writeToFile fails with error = null

我在 XCode 模拟器 (v6.4) 中有一个应用程序 运行;这是相关代码:

            NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

        //  read the file back into databuffer...
        NSFileHandle *readFile = [NSFileHandle fileHandleForReadingAtPath:[documentsPath stringByAppendingPathComponent: @"Backup.txt"]];
        NSData *databuffer = [readFile readDataToEndOfFile];
        [readFile closeFile];

        // compress the file
        NSData *compressedData = [databuffer gzippedData] ;

        // Write to disk
        NSString *outputPath = [NSString stringWithFormat:@"%@/%@%@.zip", documentsPath, venueName, strDate];
        _BackupFilename = fileName;  //  save for upload

        NSFileHandle *outputFile = [NSFileHandle fileHandleForWritingAtPath:outputPath];
        NSError *error = nil;

        //  write the data for the backup file
        BOOL success = [compressedData writeToFile: outputPath options: NSDataWritingAtomic error: &error];

        if (error == nil && success == YES) {
            NSLog(@"Success at: %@",outputPath);
        }
        else {
            NSLog(@"Failed to store. Error: %@",error);
        }

        [outputFile closeFile];

我正在尝试通过获取文件、压缩文件然后将其写出来创建文件备份。我收到错误 存储失败。错误:(空));为什么没有返回错误代码就失败了?

这里有很多错误。开始。将您的 if 语句更改为:

if (success) {

永远不要明确地将 BOOL 值与 YESNO 进行比较。

您也从不使用 outputFile,因此删除该代码。它可能会干扰对 writeToFile:.

的调用

而且使用文件句柄读取数据没有意义。只需使用 NSData dataWithContentsOfFile:.

并且不要使用 stringWithFormat: 构建路径。

总的来说,我会把你的代码写成:

NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

//  read the file back into databuffer...
NSString *dataPath = [documentsPath stringByAppendingPathComponent:@"Backup.txt"]];
NSData *databuffer = [NSData dataWithContentsOfFile:dataPath];

// compress the file
NSData *compressedData = [databuffer gzippedData];

// Write to disk
NSString *outputName = [NSString stringWithFormat:@"%@%@.zip", venueName, strDate];
NSString *outputPath = [documentsPath stringByAppendingPathComponent:outputName];

//  write the data for the backup file
NSError *error = nil;
BOOL success = [compressedData writeToFile:outputPath options:NSDataWritingAtomic error:&error];

if (success) {
    NSLog(@"Success at: %@",outputPath);
} else {
    NSLog(@"Failed to store. Error: %@",error);
}

因为 success 仍然是 NOerror 仍然是 nil,那么很可能这意味着 compressedDatanil。这可能意味着 databuffernil,这意味着 Documents 文件夹中没有名为 Backup.txt(大小写)的文件。