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

标签 objective-c ios nsfilemanager read-write

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

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/

相关文章:

iphone - NSNumber、设置和检索

ios - 架构 x86_64 的重复符号 _GSDK_GTMNSDataZLibExportToSuppressLibToolWarning

objective-c - 在 Cocoa 中重命名文件?

ios - NSFileManager removeItemAtPath 多次调用时会删除整个文件夹

ios - 如何从 32 位和 64 位的 slider 中提取值?

objective-c - 无法将文件从包复制到文档目录,为什么 fileExistsAtPath 返回错误?

ios - 在 xcode 中实现登录屏幕后滑出菜单栏

iphone - 如何将 iPhone 摇动手势检测限制在特定情况下?

ios - 如何根据图像大小设置高度的单元格

ios - Facebook 请求示例项目