首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正确使用NSFileHandle

正确使用NSFileHandle
EN

Stack Overflow用户
提问于 2013-07-16 23:53:37
回答 1查看 1.2K关注 0票数 0

所以今天早上我遇到了一个非常奇怪的问题。我有一个随着时间的推移不断增长的NSMutableString,它偶尔会将自己保存到磁盘上,基本上会创建一个不断增长的文本文件。直到几个小时前,它一直工作得很好。顺便说一下,我也没有修改这个方法中的任何代码。这是我使用的代码,NSMutableString名为stringToSave:

代码语言:javascript
复制
- (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仍然是空的。有没有人看到我在上面保存数据的方式有什么问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-17 00:03:46

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

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17681322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档