iphone - 如何将文件保存到文档文件夹中?

标签 iphone nsfilemanager nsdocumentdirectory

我正在尝试将数据保存在 iPhone 5.1 模拟器上的文档文件夹中。

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myData.json"];

if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
    NSLog(@"Writable");
}else {
    NSLog(@"Not Writable");
}

我总是“不可写”。 任何想法?请帮助我。

最佳答案

可能是因为您还没有创建该文件,所以您测试的文件不存在。 :)

您可以这样做来查找问题,

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory, @"myData.json"];
NSLog(@"filePath %@", filePath);

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // if file is not exist, create it.
    NSString *helloStr = @"hello world";
    NSError *error;
    [helloStr writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
}

if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath]) {
    NSLog(@"Writable");
}else {
    NSLog(@"Not Writable");
}

关于iphone - 如何将文件保存到文档文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11053842/

相关文章:

iphone - iPhone 和 iPad 的部署如何进行?

iOS - Swift 我如何知道 copyItemAtPath 何时完成?

path - 如何将代码 objective-c 转换为 Swift 以保存图像?

ios - UITableView(在 UIScrollView 内部)didSelectRowAtIndexPath : not being called on first tap

javascript - iPhone - 在页面加载时隐藏地址栏

iphone - Xcode,只检索带有字母 A 的地址簿姓氏(依此类推)

ios - NSFileManager,如何判断一个文件或目录是否可以删除?

copy - iOS9 NSFileManager 请求在 Documents 目录中保存文件的权限

ios - 由于文档文件夹中的 sqlite 数据库被苹果拒绝

ios - 访问保存到设备 writeToFile 的文件