我想将一些历史记录保存并加载到文本文件
我使用此代码
- (void) saveHistory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
[resultWindow.text writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL];
}
- (void) loadHistory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
if (resultWindow.text == nil) {
resultText = @"";
resultWindow.text = resultText;
}
resultWindow.text = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
}
文件保存好!但是当我加载resultWindow.text
为空(0x00000000)
答案 0 :(得分:0)
这是其中一种情况,其中进行一些简单的错误检查可能真的可以帮到你。我在这里展示的内容可能有点过多,但与此同时,几乎总是的错误检查可以帮助程序员提供更好的性能。
- (void) saveHistory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
if(resultWindow)
{
if(filePath)
{
NSError * error = NULL;
BOOL success = [resultWindow.text writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:&error];
if(success == NO)
{
// success would be NO if the file did *not* get successfully written out
NSLog( @"error in writing file to %@ - %@", filePath, [error localizedDescription]);
}
} else {
NSLog( @"filePath is mysteriously null");
}
} else {
NSLog( @"why is resultWindow null during saveHistory??");
}
}
- (void) loadHistory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"];
if(resultWindow)
{
if(filePath)
{
NSError * error = NULL;
resultWindow.text = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
if(resultWindow.text == NULL)
{
NSLog( @"error in reading file from %@ - %@", filePath, [error localizedDescription]);)
}
} else {
NSLog( @"filePath is mysteriously null");
}
} else {
NSLog( @"why is resultWindow null during loadHistory??");
}
}