我遇到了一个带有文本字段值的cocoa应用程序的问题,并将其写入文件.使用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];
谢谢你的帮助
问题是你~
在路径中有一个波浪号.~
由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];