在应用程序文档文件夹中存储和获取文档 [英] Store and fetch documents in/from app documents folder

查看:68
本文介绍了在应用程序文档文件夹中存储和获取文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个文本编辑器应用程序,我正在尝试将 NSString 作为 NSData 存储在文档文件夹中的文件中,例如我希望能够存储一个文件myText.java".

Im writing a text editor app and im trying to store a NSString as NSData in files in the documents folder, for example i want to be able to store a file "myText.java".

我的代码在模拟器上工作.但是,在设备上似乎创建了一个文件,但是当我稍后尝试从文件加载数据时,我什么也没得到.

My code work on the Simulator. However, on the device a file seems to be created, but when I later try to load the data from the files i get nothing.

我是否必须设置一些项目设置才能启用设备上的文档目录,还是我的代码有误?

Do i have to set some project setting to enable the documents directory on device or is my code wrong?

这是我的商店代码:

-(void) saveFile:(NSString*)file{
    if (![file isEqual:@"Empty"]) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:file];

        [[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil];
        NSLog(@"File: %@", fullFilePath); 
        //Above LOGS: /var/mobile/Applications/2310F459-282C-4488-AE24-D5795168F85A/Documents/fg

        //save content to the documents directory
        NSLog(@"Saving: %@", codeView.text);
        // Logs the data i want to store
        [[codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES];
    }
}

这是我的加载文件代码:

Here is my load file code:

-(void) loadFile:(NSString*)filename{
    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 *file = [documentsDirectory stringByAppendingPathComponent:filename];
    if ([[NSFileManager defaultManager] fileExistsAtPath:file]) {
        NSLog(@"File found");
        //Yes the file is found

        theDelegate.fileData = [NSData dataWithContentsOfFile:file];
        NSLog(@"Data:%@",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:file] encoding:NSASCIIStringEncoding]);
        // On device and simulator data is found

        [theDelegate.codeView setText:[[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]];
        //codeView does not get updated with the data.
        //NSLog([[NSString alloc] initWithData:theDelegate.fileData encoding:NSASCIIStringEncoding]);
        [theDelegate setTitle:filename];
        [theDelegate setHasOpenFile:YES];
        [theDelegate.codeView setEditable:theDelegate.hasOpenFile];
        [theDelegate.codeView setNeedsDisplay];
        [self setLanguage:filename];
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File error!" message:@"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil, nil];
       [alert show];
    }
}

推荐答案

不,您不必启用设置即可使用文档目录.您的代码可能有也可能没有错误,在任何情况下都很难阅读并且不是很干净(抱歉这么说.)

No, you don't have to enable a setting to use the documents directory. There might or might not be an error with your code, in any case it's hard to read and not very clean (apologies for saying this.)

尝试只做一次.我冒昧地重写了你的代码,把它清理干净.然后我用手机上的示例应用程序对其进行了测试,它运行良好.

Try to do everything just once. I took the liberty of rewriting your code a bit, to clean it up. I then tested it with a sample app on my phone, and it works perfectly.

代码重写:

-(void) saveFile:(NSString*)filename{
    if (![filename isEqual:@"Empty"]) {

        NSString *fullFilePath = [self getFullFilePath:filename];

        [[NSFileManager defaultManager] removeItemAtPath: fullFilePath error: nil];
        NSLog(@"File: %@", fullFilePath);

        //save content to the documents directory
        NSLog(@"Saving: %@", self.codeView.text);
        // Logs the data i want to store
        [[self.codeView.text dataUsingEncoding:NSASCIIStringEncoding] writeToFile:fullFilePath atomically:YES];
    }
}

上面的代码没问题,添加了辅助函数之后.

The above code is fine, after adding the helper function.

-(void) loadFile:(NSString*)filename{

    NSString *fullFilePath = [self getFullFilePath:filename];

    if ([[NSFileManager defaultManager] fileExistsAtPath:fullFilePath]) {
        NSLog(@"File found");
        //Yes the file is found

        NSLog(@"Data:%@",[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]);
        // On device and simulator data is found

        [theDelegate.codeView setText:[[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fullFilePath] encoding:NSASCIIStringEncoding]];

        [theDelegate setTitle:filename];
        [theDelegate setHasOpenFile:YES];
        [theDelegate.codeView setEditable:theDelegate.hasOpenFile];
        [theDelegate.codeView setNeedsDisplay];
        //[self setLanguage:filename];
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"File error!" message:@"An error occured when trying to load the selected file." delegate:self cancelButtonTitle:@"OK!" otherButtonTitles:nil, nil];
        [alert show];
    }
}

在您的旧代码中,如果引用较弱,theDelegate.fileData = [NSData dataWithContentsOfFile:file]; 可能存在问题.由于我认为您将始终在 codeView 中拥有代码,因此似乎没有必要先将其存储在成员变量中.此外,这可能会导致更多错误.

In your old code, there might have been a problem with theDelegate.fileData = [NSData dataWithContentsOfFile:file];, if the reference is weak. Since I presume you'll always have the code in codeView, it seems unnecessary to first store it in a member variable. Also, this might lead to more bugs.

以下是一个辅助函数,因此您不要在两个函数中做完全相同的事情,因为这可能会导致错误.

The following is a helper function, so that you don't do the exact same thing in both functions, as it might lead to bugs.

-(NSString*) getFullFilePath:(NSString*)filename {
    NSArray *paths = NSSearchPathForDirectoriesInDomains
    (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullFilePath = [documentsDirectory stringByAppendingPathComponent:filename];

    return fullFilePath;

}

这篇关于在应用程序文档文件夹中存储和获取文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆