2012-10-25 60 views
1

我正在嘗試將文件寫入臨時目錄。我這樣做:寫入臨時目錄不起作用

NSString *_location = NSTemporaryDirectory(); 
NSString *_guid = [[NSCalendarDate calendarDate] descriptionWithCalendarFormat:@"%m%d%Y%H%M%S%F"]; 
_guid = [_guid stringByAppendingString:@".png"]; 
NSString *_tempFilePath = [NSString stringWithFormat:@"%@/%@", _location, _guid]; 
NSData *_temp_data = [imgRep representationUsingType: NSPNGFileType properties: nil]; 
[_temp_data writeToFile:_tempFilePath atomically: NO]; 

但它不適用於我。它不創建文件。有什麼問題?

P.S.我試圖在NSTemporaryDirectory中創建一個具有唯一名稱的目錄,然後在那裏寫入一個文件,但它也不起作用。


我注意到它不會在任何地方創建文件。試圖將位置設置爲用戶的文檔文件夾,但它不工作。

+0

'_uid'和'_guid'? – trojanfoe

+0

對不起,我在重寫代碼時犯了錯誤 – hockeyman

回答

2

路徑用於寫入圖像是不正確的:

NSString *_tempFilePath = [NSString stringWithFormat:@"%@/%@", _location,_guid]; 

OR

NSString *_tempFilePath = [location stringByAppendingPathComponent:@"%@",guid]; 
+0

'[NSString stringByAppendingPathComponent]'更好...... – trojanfoe

+0

它仍然不會創建文件。 _tempFilePath看起來像這樣: ''/var/folders/_n/fqxvr8rd543f3c9mvbd30_y40000gp/T/10252012155853582.png,但該文件未創建 – hockeyman

+0

現在檢查編輯答案 –

2

如果你寫裏面潛在的新目錄中的文件,你必須先創建目錄:

[[NSFileManager defaultManager] createDirectoryAtPath:_directoryPath 
          withIntermediateDirectories:YES 
              attributes:nil error:nil]; 

[_myData writeToFile:[_directoryPath stringByAppendingPathComponent:_fileName] 
      atomically:YES]; 
+0

我沒有創建一個目錄,我只是試圖寫一個文件到OS X已經創建的臨時目錄。 – hockeyman

+0

@JuliusPetraška你不是在Prince的回答評論中說它在你創建目錄但不是當你不? – trojanfoe

+0

我的意思是我可以在那裏創建一個目錄,但是我不能創建一個文件。 – hockeyman