[Solved] iOS write to a txt [duplicate]


Try this:

-(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]);
        }
    }
}

And to read the score back in, you can do:

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 = @"";
}

11

solved iOS write to a txt [duplicate]