Objective-C 使用字符串创建文本文件
我正在尝试在桌面上创建一个包含字符串内容的文本文件。我不确定我做得是否正确,我没有收到错误,但它也不起作用......
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];
I'm trying to create a text file with the contents of a string to my desktop. I'm not sure if I'm doing it right, I don't get errors but it doesn't work either...
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
NSString *desktopDirectory=[paths objectAtIndex:0];
NSString *filename = [desktopDirectory stringByAppendingString: @"file.txt"];
[myString writeToFile:filename atomically:YES encoding: NSUTF8StringEncoding error: NULL];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不知道是否收到任何错误,因为您忽略了 -writeToFile:... 方法返回的 YES/NO 值,并且没有给它提供错误指针来记录任何可能的失败。如果该方法返回“否”,您将检查(并处理或呈现)错误以查看出了什么问题。
据猜测,失败是由于您构建的路径造成的。尝试 -stringByAppendingPathComponent: 而不是 -stringByAppendingString: ... 这及其相关方法可以正确处理路径。
该文件可能实际上正在创建(即,您可能最终不会收到任何错误)。我的猜测是该文件是在“~/Desktopfile.txt”之类的地方创建的,因为您使用 -stringByAppendingString: 不会将该字符串视为斜杠分隔的路径。检查你的主文件夹 - 我敢打赌该文件就在那里。
You don't know if you're getting any errors because you're ignoring the returned YES/NO value of the -writeToFile:... method, and giving it no error pointer into which to record any possible failure. If the method returns NO, you'd check (and handle or present) the error to see what went wrong.
At a guess, the failure is due to the path you constructed. Try -stringByAppendingPathComponent: instead of -stringByAppendingString: ... this and its related methods properly handle paths.
The file probably is actually being created (ie, you might not be getting any errors after all). My guess is the file is created somewhere like "~/Desktopfile.txt" since your use of -stringByAppendingString: doesn't consider the string as slash-separated path. Check your home folder - I'll bet the file's there.
问题是桌面目录字符串以空结尾(没有 /)。使用 UIAlertview 查看(在 iPhone 上)。
the problem is that the desktop directory string ends in nothing (no /). Check this out (on an iPhone) by using UIAlertview.