Search code examples
cocoastringtext-filesstringwithformat

Use stringWithFormat: as a file path in cocoa


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


Solution

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