繁体   English   中英

正确使用NSFileHandle

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM