[英]Using NSFileHandle Properly
所以今天早上我遇到了一個很奇怪的問題。 我有一個NSMutableString
,它會隨着時間的流逝而不斷增長,並且偶爾會保存到磁盤中,基本上創建了一個不斷增長的文本文件。 直到幾個小時前,它一直運行良好。 順便說一句,我也沒有更改方法中的任何代碼。 這是我正在使用的代碼, NSMutableString
稱為stringToSave:
- (void)saveToTextFile {
NSLog(@"SaveTextToFile called");
// Get Current date and time:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:@"hh:mm"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
NSString *dateToBeDisplayed = [NSString stringWithFormat:@"Date: %@, Time: %@.", theDate, theTime];
// Create text to save, and save it.
stringToSave = [NSString stringWithFormat:@"\n %@ ",dateToBeDisplayed];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"mynotes"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[stringToSave dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
// Check what's saved there.
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:nil];
NSLog(@"File Content: %@", content);
NSLog(@"stringtosave: %@", stringToSave);
}
奇怪的是, stringToSave
始終在NSLog中包含適當的數據,而content
仍然為空。 有人在我上面保存數據的方式中看到任何錯誤嗎?
啟動時文件是否存在? https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsfilehandle_Class/Reference/Reference.html說,如果該文件不存在,則您的fileHandleForWritingAtPath:返回nil。
如果您刪除並重新安裝應用程序(在模擬器上的設備上),則該文件將不存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.