2015-09-27 104 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