【问题标题】:Read Text File in Document Folder - Iphone SDK读取文档文件夹中的文本文件 - Iphone SDK
【发布时间】:2011-02-12 04:11:43
【问题描述】:

我有以下代码:

    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]];
  • textviewerdownload 是显示文件文本的textview。实际文件名存储在名为recentDownloadNSUserDefault 中。

  • 当我构建它时,我点击它下面的button,然后点击我的应用程序crashes

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

【问题讨论】:

  • 如果语法有问题,您的代码将无法编译;你不会到运行它并看到它崩溃的阶段。要调试崩溃,请使用调试器;它应该告诉你你是如何坠毁的以及在哪里坠毁的。

标签: ios iphone objective-c cocoa documents


【解决方案1】:

对于文本文件的读/写,请查看url

【讨论】:

  • 确保在 info.plist 中将布尔标志“UIFileSharingEnabled”设置为 YES
【解决方案2】:
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];

这对我有用

不管怎样,谢谢大家..

【讨论】:

    【解决方案3】:

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

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    
    NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"recentDownload.txt"]; 
    

    【讨论】:

    • 好的,我更改了一些编码.. 我的应用程序仍然崩溃.. 这是我的 IBAction 下的代码:heliotop.org/code.rtf 另外,如果最近的文件不是,我将如何执行 if 语句一个扩展名为“txt”的文件,它会返回,如果它是那么导致一个动作..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多