iOS:保存到文件适用于模拟器,但不适用于设备

发布于 2024-12-10 10:46:01 字数 634 浏览 0 评论 0原文

我的应用程序将用户信息/首选项的加密数据写入文件中,并在下次打开应用程序时从该文件中读取。

写入文件:

- (BOOL)writeFile:(NSString *)data:(NSString *)fileName {
  return [data writeToFile:fileName
                atomically:YES
                  encoding:NSUTF8StringEncoding error:nil];
}

读取文件:

- (NSString *)readFile:(NSString *)fileName {
  NSData *data = [NSData dataWithContentsOfFile:fileName];
  NSString *str = [[[NSString alloc] initWithData:data
                                         encoding:NSUTF8StringEncoding] autorelease];
  return str;
}

这在模拟器上运行良好。文件按预期写入和读取。我需要设置什么才能在设备上读取/写入文件吗?

My app writes an encrypted data of the user info/preferences into a file, and reads from that file the next time the app is opened.

Writing a file:

- (BOOL)writeFile:(NSString *)data:(NSString *)fileName {
  return [data writeToFile:fileName
                atomically:YES
                  encoding:NSUTF8StringEncoding error:nil];
}

Reading a file:

- (NSString *)readFile:(NSString *)fileName {
  NSData *data = [NSData dataWithContentsOfFile:fileName];
  NSString *str = [[[NSString alloc] initWithData:data
                                         encoding:NSUTF8StringEncoding] autorelease];
  return str;
}

This works fine on the emulator. The files are written and read as expected. Is there anything I have to setup for file read/write on devices?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

同尘 2024-12-17 10:46:01

文件名必须位于文档目录中。模拟器不会像设备那样对写入文件的位置有那么多限制。

按如下方式获取文档目录:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myfilename.extension"];

将其传递到上面的函数中,应该没问题。

The filename has to be in the documents directory. The simulator won't have as many restrictions on where it can write files as the device does.

Obtain the documents directory as follows:

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:@"myfilename.extension"];

Pass this into your functions above and you should be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文