2014-05-25 23 views
-5

我想在一個txt寫的,但我的代碼沒有工作...的iOS寫一個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]; 
+0

什麼是「不工作」呢?它是否編譯?它會崩潰嗎?它是否有效,但不是寫作「測試」,而是寫下「所有的黑色史蒂夫喬布斯IPHONES的主人!」? – nhgrif

+0

您無法在iOS中的應用程序包內寫入文件。你應該把你的文件寫入〜/ Library/Preferences或其他地方。 –

+0

感謝您的答案。 這不工作,因爲沒有寫在我的txt,但我的應用程序運行沒有錯誤! – user3657063

回答

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

謝謝,但它不工作。而我的控制檯是空的:/ 但是,如果我刪除「!」在if中,我有這樣的信息:無法將文件寫入/ Users/ludovic/Library/Application Support/iPhone Simulator/7.1/Applications/10B15625-FFAE-4A11-AF35-1946CE978426/Library/Preferences/bestScore.txt因爲null) – user3657063

+0

我更改了我的代碼,以便您可以看到它已成功保存。如果文件成功保存,「writeToFile'」返回YES,如果文件寫入出了問題,則返回NO。 –

+0

現有文件bestScore.txt的權限是多少?如果刪除該文件會發生什麼情況,寫入操作會成功嗎? –