0

我有一个在 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];

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

4

1 回答 1

2

这里有很多问题。开始。将您的if声明更改为:

if (success) {

永远不要明确地将BOOL值与YESor进行比较NO

您也永远不会使用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,那么这很可能就是那个compressedData意思nil。这可能意味着databuffernil意味着文件夹中没有名为Backup.txt(大小写问题)的Documents文件。

于 2015-09-27T16:33:42.210 回答