0

我想保存一些历史记录并将其加载到文本文件中

我使用此代码

    - (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)

4

1 回答 1

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??");
    }
}
于 2013-02-10T22:19:44.720 回答