5

我在下面有这段代码:

    NSString *fileName = [[NSUserDefaults standardUserDefaults] objectForKey:@"recentDownload"];
    NSString *fullPath = [NSBundle pathForResource:fileName ofType:@"txt" inDirectory:[NSHomeDirectory() stringByAppendingString:@"/Documents/"]];
    NSError *error = nil;

    [textViewerDownload setText:[NSString stringWithContentsOfFile:fullPath encoding: NSUTF8StringEncoding error:&error]];
  • textviewerdownloadtextview显示文件中的文本。实际文件名存储在NSUserDefault名为recentDownload.

  • 当我构建它时,我单击button它下面的那个,以及我的应用程序crashes

  • 语法有什么问题还是只是简单的错误?

4

3 回答 3

9

该类NSBundle用于在您的应用程序包中查找内容,但 Documents 目录位于包之外,因此您生成路径的方式将不起作用。试试这个:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask,
                                                     YES);

NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
于 2010-04-25T20:37:03.817 回答
6
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
    {
        NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
    }       

    //Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];

这对我有用

总之谢谢大家。。

于 2010-12-09T11:13:25.970 回答
2

对于从文本文件读/写检查这个url

于 2011-05-16T07:40:12.170 回答