iOS:保存到文件适用于模拟器,但不适用于设备
我的应用程序将用户信息/首选项的加密数据写入文件中,并在下次打开应用程序时从该文件中读取。
写入文件:
- (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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
文件名必须位于文档目录中。模拟器不会像设备那样对写入文件的位置有那么多限制。
按如下方式获取文档目录:
将其传递到上面的函数中,应该没问题。
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:
Pass this into your functions above and you should be fine.