1

テキスト フィールドの値を取得してファイルに書き込むココア アプリケーションに問題があります。ファイル パスは、stringWithFormat: を使用して作成され、2 つの文字列を結合します。何らかの理由でファイルが作成されず、コンソールには何も表示されません。これが私のコードです:

//Get the values of the text field
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];

//Use stringWithFormat: to create the file path
NSString *filePath = [NSString stringWithFormat:@"~/Library/Application Support/Test/%@.txt", fileName];

//Write the username to filePath
[username writeToFile:filePath atomically:YES];

助けてくれてありがとう

4

2 に答える 2

9

~問題は、パスにチルダがあることです。シェル~によってユーザーのホーム ディレクトリに展開されますが、これは Cocoa では自動的には行われません。を使用します。これはうまくいくはずです:-[NSString stringByExpandingTildeInPath]

NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
NSString *fileName = [fileName stringByAppendingPathExtension:@"txt"];    // Append ".txt" to filename
NSString *filePath = [[@"~/Library/Application Support/Test/" stringByExpandingTildeInPath] stringByAppendingPathComponent:fileName];    // Expand '~' to user's home directory, and then append filename
[username writeToFile:filePath atomically:YES];
于 2010-03-13T17:03:43.890 に答える
3

mipadiの返信に追加すると、チルダを解決するよりも多くのことを行い、より多くの問題を解決できるため、 -[NSString stringByStandardizingPath] を使用することをお勧めします。

于 2010-03-13T17:18:52.420 に答える