我在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];
我尝试通过获取文件,压缩文件然后将其写出来创建文件的备份。我收到错误无法存储。错误:(null));为什么没有返回错误代码就失败了?
答案 0 :(得分:2)
这里有很多不妥之处。开始。将您的if
声明更改为:
if (success) {
绝不明确将BOOL
值与YES
或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
仍为NO
且error
仍为nil
,因此很可能这意味着compressedData
为nil
。这可能意味着databuffer
为nil
,这意味着Backup.txt
文件夹中没有名为Documents
的文件(案例很重要)。