在 Objective C 中创建文件时出现未知错误
我正在创建一个Mac应用程序,需要创建一个包含另一个文件内容的文件,我创建它的方式如下:
NSString *p = @"/AfilethatEXISTS.plist";
NSString *user1 = @"~/Library/MyApp/myFile";
NSString *pT1 = [user1 stringByExpandingTildeInPath];
[[NSFileManager alloc] createFileAtPath:[NSURL URLWithString:pT1] contents:[NSData dataWithContentsOfFile:p] attributes:nil];
但是没有返回错误,它没有创建文件?
I'm creating a mac app that needs to create a file with the contents of another file, i'm creating it as follows:
NSString *p = @"/AfilethatEXISTS.plist";
NSString *user1 = @"~/Library/MyApp/myFile";
NSString *pT1 = [user1 stringByExpandingTildeInPath];
[[NSFileManager alloc] createFileAtPath:[NSURL URLWithString:pT1] contents:[NSData dataWithContentsOfFile:p] attributes:nil];
However returning no error, its not creating the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这段代码有几个问题,但没有足够的上下文来告诉您出了什么问题。
首先, / 中不应该直接存在文件。该目录应该是神圣不可侵犯的,许多用户在没有管理员访问权限的情况下将无法写入该目录。
其次,应该通过 NSString 和 NSURL 上的路径操作 API 来管理路径。
接下来,
pT1
并不是真正的 URL,即URLWithString:
可能会返回 nil。请改用fileURLWithPath:
。最后,该代码中没有任何错误检查,因此无法告诉您如何发现没有错误。你检查了什么?
There are several things wrong with this code, but not enough context to tell you what is going wrong.
First, there should never be a file in / directly. That directory should be sacrosanct and many users will not be able to write to that directory without admin access.
Secondly, paths should be managed via the path manipulation APIs on NSString and NSURL.
Next,
pT1
isn't really an URL and that isURLWithString:
may be returning nil. UsefileURLWithPath:
instead.Finally, there isn't any error checking in that code and, thus, there is no way to tell how you might have discovered no error. What have you checked?
首先,您错误地创建了文件管理器实例。要创建一个新实例,您需要分配并初始化它。
您正在尝试传递一个 NSURL 对象,该对象将无法正确创建,因为您用来创建它的字符串不是 URL。但这并不重要,因为即使创建了 NSURL,-createFileAtPath:contents:attributes: 需要一个 NSString -直接通过pT1就可以了。
更好的是,由于您基本上只是将 p 复制到 pT1,因此可以使用 NSFileManager 方法来执行此操作。它不仅在概念上更适合,而且还使您有机会检查返回的 NSError 对象以查看出了什么问题(如果有的话)。
First off, you're creating the file manager instance incorrectly. To create a new instance, you need to both allocate and initialize it.
You're trying to pass an NSURL object, which won't be created correctly since the string you're using to create it with isn't a URL. But that doesn't matter anyway, because even if the NSURL was created, -createFileAtPath:contents:attributes: expects an NSString - just pass pT1 directly.
Better still, since you're basically just copying p to pT1, use the NSFileManager method for doing that. Not only is it conceptually a better fit, it also gives you a chance to examine a returned NSError object to see what (if anything) went wrong.