【问题标题】:Using NSFileHandle Properly正确使用 NSFileHandle
【发布时间】:2013-07-14 21:59:10
【问题描述】:

所以我今天早上遇到了一个非常奇怪的问题。我有一个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 仍然是空的。有人看到我在上面保存数据的方式有什么问题吗?

【问题讨论】:

    标签: ios objective-c cocoa-touch nsfilemanager


    【解决方案1】:

    启动时文件是否存在? https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsfilehandle_Class/Reference/Reference.html 表示如果文件不存在,那么您的 fileHandleForWritingAtPath: 返回 nil。

    如果您删除并重新安装您的应用程序(无论是在模拟器上的设备上),该文件将不存在。

    【讨论】:

    • 哦,这可能是问题所在,因为这只是在我重新安装应用程序时才开始发生的。有趣的。如果它不存在,你知道我如何创建它吗?
    • 使用 fileExistsAtPath: 和 createFileAtPath: (参见developer.apple.com/library/ios/#documentation/Cocoa/Reference/…的文档)
    • fileExistsAtPath 对我来说已经坏了——Apple 的文档建议他们不在乎(头文件特别说不要使用这种方法,因为它不能可靠地工作)
    猜你喜欢
    • 2016-04-29
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    相关资源
    最近更新 更多