-[NSString writeToFile:] 不改变文件的内容
我正在尝试写入资源中的文件“index.html”。我可以毫无问题地加载文件,但我似乎无法写入它。没有任何内容显示为错误,它只是不写入。该应用程序不会中止或发生任何事情,但是当我重新加载文件时,没有任何变化。
我的编写代码:
NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
NSString *path = [thisBundle pathForResource:@"index" ofType:@"html"];
NSString *myString = [[NSString alloc] initWithFormat:@""];
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
我的加载代码:
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
我做错了什么?
I'm trying to write to a file "index.html" that I have in my resources. I can load the file with no problem, but I can't seem to write to it. Nothing is showing up as an error, it simply doesn't write. The app doesn't abort or anything, but when I re-load the file nothing has changed.
My writing code:
NSBundle *thisBundle = [NSBundle bundleForClass:[self class]];
NSString *path = [thisBundle pathForResource:@"index" ofType:@"html"];
NSString *myString = [[NSString alloc] initWithFormat:@""];
[myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
My loading code:
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
现有代码不会覆盖
index.html
文件的原因是应用程序无法覆盖其资源。 Apple 的 iOS 应用程序编程指南说:相反,写入您的文档目录。您可以像这样获取文档目录的路径:
请注意,iOS simple 上的
NSHomeDirectory()
返回应用程序包的路径。一旦获得了文档目录的路径,您就可以写入资源,比如说index.html,如下所示:请注意,我将您的
error:
参数更改为nil
。这实际上不会影响任何东西,但通常的做法是使用 nil 来指示 NULL Objective-C 对象。The reason that your existing code doesn't overwrite the
index.html
file is that an application can not overwrite its resources. Apple's iOS Application Programming Guide specifically says:Instead, write to your documents directory. You can get the path to the documents directory like this:
Note that
NSHomeDirectory()
on iOS simple returns the path to your application's bundle. Once you have the path to the documents directory, you can write to a resource, let's say index.html, as follows:Note that I changed your
error:
parameter tonil
. This will not actually affect anything, but it is common practice to usenil
to indicate NULL Objective-C objects.尝试在执行操作之前将文件移动到文档目录,这堆代码使工作
.h
.m
最后,您应该在类似的情况下使用它:
Try to move your file to Documents Directory before perform the operation this bunch of code makes the work
.h
.m
Finally you should use it in something like that: