2015-09-27 88 views
0

我有一个应用程序在XCode模拟器(v6.4)中运行;这是相关代码:writeToFile失败,错误= null

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

我试图通过采取文件,压缩它,然后写出来,以创建一个文件的备份。我收到一个错误无法存储。错误:(null));为什么它没有返回错误代码失败?

+0

嗨Rick ...输出文件用作“恢复”功能的输入...我会做出更改并回复给您... 注意:我刚刚保存了我的评论,现在全部你的消失了吗?我如何让他们回来? – SpokaneDude

回答

2

这里有很多错误。开始。改变你的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(案件事项)的文件。

+0

使用你的代码,我得到了同样的东西(失败存储,错误:(空)) – SpokaneDude

+0

然后最有可能'compressedData'是'nil'这可能意味着'databuffer'是'nil'这意味着没有文件在Documents文件夹中命名为Backup.txt。 – rmaddy

+0

谢谢Rick ...我会遵循它...... D – SpokaneDude