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];

    }

ファイル保存OK!しかし、ロードするresultWindow.textと空です(0x00000000)

4

1 に答える 1

0

これは、いくつかの簡単なエラー チェックを実行すると本当に役立つ場合の 1 つです。ここで示していることは少し多すぎるかもしれませんが、同時に、ほとんどの場合、エラー チェックプログラマーがパフォーマンスを向上させるのに役立ちます。

- (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 に答える