gpt4 book ai didi

objective-c - 如何使用 iOS、模拟器和设备读取/写入文件?

转载 作者:技术小花猫 更新时间:2023-10-29 10:58:11 25 4
gpt4 key购买 nike

因为我需要在我的应用程序启动时读取文件,有时在使用它时写入它,所以我尝试通过以下方式访问它:

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];
NSLog(@"%@",dataFile);

而应该在我的项目文件夹中的文件却在模拟器文件夹中:

2012-06-13 17:36:56.398 MyFileApp[610:15203] /Users/Rob/Library/Application Support/iPhone Simulator/5.1/Applications/1FFD4436-DCCA-4280-9E47-F6474BEE0183/MyFileApp.app/myFile.txt

那么如果我想在模拟器和真机上读写,我该怎么办?

谢谢你的建议

最佳答案

要从包中读取文件,请执行以下操作

NSString *dataFile = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"txt"];

从您的沙箱存储(文档)中读取它

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
NSString *dataFile = [NSString stringWithContentsOfFile:docPath
usedEncoding:NSUTF8StringEncoding
error:NULL];

写入文件夹

NSString *docPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/YourFile.txt"];
[dataFile writeToFile:docPath
atomically:YES
encoding:NSUTF8StringEncoding
error:NULL];

请注意,您将无法在应用程序的捆绑文件夹中写入该文件

关于objective-c - 如何使用 iOS、模拟器和设备读取/写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11078647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com