【发布时间】:2014-03-28 21:23:06
【问题描述】:
我遇到了一个问题,但我找不到任何相关信息。
我有一些代码可以在 iOS 的 Documents 文件夹中写入文件。检查了 Apple 文档,似乎我想将文件放在其中以便下次发布时可用。
这是我正在使用的代码:
- (void) writeToTextFile:(NSString *)logMessage inFile:(NSString *)fileName
{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *filePath = [NSString stringWithFormat:@"%@/%@.txt", documentsDirectory, fileName];
NSLog(@"TEST path: %@", filePath);
//save logMessage to the documents directory
[logMessage writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
}
现在我正在对这些方法进行单元测试。它在 iOS 7.0.3 模拟器上运行良好,但当我切换到 iOS 6.0 时,它不再运行了。
其实我发现“Application Support/iPhone Simulator/6.0/”里面没有Documents文件夹,但是7.0.3文件夹里有一个。
我真的找不到在 6 和 7 之间应该如何处理写入文件的任何差异。我是否应该测试文件夹是否存在,如果不存在则创建它?
【问题讨论】:
-
您的
filePath无效。要创建文件路径,请使用stringByAppendingPathComponent方法。喜欢NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName]; -
在问这里之前,你可能应该添加一个错误变量并在 iOS 6 中读取它,然后告诉我们它在说什么。假设它不只是直接告诉你出了什么问题。
-
它告诉我找不到目录
-
经过测试的
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];它给了我完全相同的路径(减去.txt)并且给了我同样的错误。但它肯定更干净!
标签: ios iphone objective-c ios6 ios7