iOS写入txt

时间:2014-05-25 12:39:01

标签: ios file-io

我想写一个txt,但我的代码不能正常工作......

这是我的代码:

-(void)bestScore{
    if(cptScore > bestScore){
        bestScore = cptScore;
        highScore.text =[[NSString alloc] initWithFormat: @" %.d", bestScore];
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bestScore" ofType:@"txt"];
        NSString *test = @"test";
        [test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
}

我的文件夹中已有一个名为bestScore.txt的文件"支持文件"

你能帮我吗?

由于

编辑: 我可以阅读我的文件" bestScore.txt"使用此代码:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"bestScore" ofType:@"txt"];
    NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    highScore.text = textFromFile;
    bestScore = [textFromFile intValue];

1 个答案:

答案 0 :(得分:0)

试试这个:

-(void)bestScore{
    if(cptScore > bestScore){
        bestScore = cptScore;
        highScore.text =[[NSString alloc] initWithFormat: @" %.d", bestScore];
        NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Preferences/bestScore.txt"];
        NSString *test = [NSString stringWithFormat:@"%@",bestStore];
        NSError *error;

       // save a new file with the new best score into ~/Library/Preferences/bestScore.txt
       if([test writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error])
       {
            // wrote to file successfully
            NSLog(@"succesfully wrote file to %@", filePath);
        } else {
            // there was a problem
            NSLog(@"could not write file to %@ because %@", filePath, [error localizedDescription]);
        }
    }
}

要重读比分,你可以这样做:

NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Preferences/bestScore.txt"];
NSString *textFromFile = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
if(textFromFile)
{
    highScore.text = textFromFile;
    bestScore = [textFromFile intValue];
} else {
    // if the file doesn't exist or if there's an error, initialize bestScore to zero
    bestScore = 0;
    highScore.text = @"";
}