views:

276

answers:

2

Hello,

I'm having a problem with a cocoa application that takes the value of a text field, and writes it to a file. The file path is made using stringWithFormat: to combine 2 strings. For some reason it will not create the file and the console says nothing. Here is my code:

//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];

Thanks for any help

+8  A: 

The problem is that you have a tilde ~ in the path. ~ is expanded by the shell to the user's home directory, but this doesn't happen automatically in Cocoa. You want to use -[NSString stringByExpandingTildeInPath]. This should work:

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];
mipadi
Thanks for the reply!
happyCoding25
+2  A: 

Adding to mipadi's reply, it's better to use -[NSString stringByStandardizingPath] since it does more - and can clean up more problems - than resolving the tilde.

Joshua Nozzi