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

~问题是路径中有波浪号。~shell扩展到用户的主目录,但这在 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 回答