4

我正在尝试将数据保存在 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");
}

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

4

4 回答 4

20

可能因为你没有创建文件,你测试的文件不存在。:)

你可以这样做来找到问题,

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");
}
于 2012-06-15T15:40:16.533 回答
5

尝试这个:

NSString *data = .... // your json representation
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myData.json"];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
于 2012-06-15T15:59:11.383 回答
3

把你[NSString stringWithFormat:]的换成[NSString stringByAppendingPathComponent:]. 这决定或破坏了你创造可行道路的能力,或者我的经验告诉我。

此外,在模拟器与真实设备上编写时会出现这种情况。当您将内容保存在错误的路径中时,模拟器比设备更宽容,而且通常您会让 I/O 工作正常,只是遇到臭名昭著的“它在模拟器中工作!” 坑。 stringWithFormat:只是一种陷入困境的方式。

于 2012-06-15T15:47:48.393 回答
1

获取文档目录路径

+(NSURL *)getDocumentsDirectoryPath
{
    return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}

将数据写入文件末尾

+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
    NSString *filePath = [NSString stringWithFormat:@"%@.text",fileName];

    NSString *path = [[self getDocumentsDirectoryPath].path
                      stringByAppendingPathComponent:filePath];
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    if(fileHandler == nil) {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
        fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
    } else {
        textTobeSaved = [NSString stringWithFormat:@"\n-----------------------\n %@",textTobeSaved];
        [fileHandler seekToEndOfFile];
    }

    [fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandler closeFile];
}
于 2017-11-02T09:21:11.027 回答