2009-11-30 16 views
11

文字列の内容をデスクトップに作成しようとしています。私はあなたがあなたのためにすべてのエラーを取得しているかどうかわからないObjective-C文字列を含むテキストファイルを作成する

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); 
NSString *desktopDirectory=[paths objectAtIndex:0]; 
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"]; 
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL]; 

答えて

13

私は右のそれをやっている場合、私はエラーを取得しないが、それは動作しませんわからないのいずれか... -writeToFile:...メソッドの返されたYES/NO値を無視し、可能性のあるエラーを記録するためのエラーポインタを与えません。メソッドがNOを返した場合は、エラーをチェックして(処理したり、表示して)、何がうまくいかなかったかを確認します。

推測すると、失敗はあなたが構築したパスに起因します。 try -stringByAppendingPathComponent:-stringByAppendingStringの代わりに:...これとその関連メソッドは適切にパスを処理します。

おそらくファイルです(結局、エラーが発生していない可能性があります)。私の推測では、あなたの-stringByAppendingStringの使用以来、ファイルは "〜/ Desktopfile.txt"のようなどこかに作成されています。文字列はスラッシュで区切られたパスとみなされません。あなたのホームフォルダを確認してください - そこにファイルがあるはずです。

39
//Method writes a string to a text file 
-(void) writeToTextFile{ 
    //get the documents directory: 
    NSArray *paths = NSSearchPathForDirectoriesInDomains 
     (NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    //make a file name to write the data to using the documents directory: 
    NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt", 
                documentsDirectory]; 
    //create content - four lines of text 
    NSString *content = @"One\nTwo\nThree\nFour\nFive"; 
    //save content to the documents directory 
    [content writeToFile:fileName 
        atomically:NO 
          encoding:NSStringEncodingConversionAllowLossy 
            error:nil]; 

} 
+0

完璧な男...ありがとう。 –

+0

これは完全に動作します – MayorMonty

+0

ありがとう、仲間!シンプルで使いやすい。 – Felipe

-3

問題は、デスクトップディレクトリの文字列が(/)で終わらないということです。これをUIAlertviewを使って(iPhone上で)チェックしてください。

+1

何ですか? 1.)あなたがしたようにするには '/'を使う必要はありません。 2.)UIAlertViewはどこにありますか?私はしません。 3)この質問はほぼ2年前に尋ねられました。 –

+0

..なぜ私たちはiOS上の「デスクトップ」と何か関係があるのでしょうか? iOSにはそのようなことはありません。 –

関連する問題