gpt4 book ai didi

cocoa - 使用 stringWithFormat : as a file path in cocoa

转载 作者:行者123 更新时间:2023-12-03 16:49:06 26 4
gpt4 key购买 nike

我在使用 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];

关于cocoa - 使用 stringWithFormat : as a file path in cocoa,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2439139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com