【问题标题】:How to store the contents of a file into an NSString?如何将文件的内容存储到 NSString 中?
【发布时间】:2014-04-29 04:30:33
【问题描述】:

这很尴尬,我看到很多问题得到了回答,我复制了很多答案,但没有人适合我,我是 Objective C 的新手,我知道这里的规则,我用谷歌搜索了它,我看到了很多目标 C、Xcode、编程、C、论坛、博客的页面,在这里,我得到了 Nuts。这是我的想法

代码:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        NSError *error = NULL;
        NSString* pathFile = [[NSBundle mainBundle] pathForResource:@"file"
                                                                  ofType:@"txt"];
        NSString* content = [NSString stringWithContentsOfFile:pathFile
                                                            encoding:NSUTF8StringEncoding
                                                               error:&error];
        if (error)
            NSLog(@"Error reading file: %@", error.localizedDescription);
        NSLog(@"%@", content);
    }
    return 0;
}

它非常简单,在原始应用程序中它很复杂,但这是我遇到麻烦的部分。

这是 buble 中的文件...

结果如下:

2014-04-28 21:45:17.213 LeerFile[6930:303] Error reading file: The file name is invalid.
2014-04-28 21:45:17.214 LeerFile[6930:303] (null)

最后是构建阶段......

伙计们,请帮我解决这个问题,我试了一下,但我不知道我做错了什么或如何解决它......

【问题讨论】:

    标签: objective-c cocoa nsstring nsbundle


    【解决方案1】:

    问题是您将文件复制到 /usr/share/man/man1/,但您正在捆绑包的资源文件夹中查找该文件。您需要将文件复制到资源文件夹中,或者将不同的路径传递给[NSString stringWithContentsOfFile:encoding:error:];。

    您还选中了“仅在安装时复制”,这意味着它不会复制调试版本中的文件。

    【讨论】:

    • 完美。我在 pathForResource 上写 /usr/share/man/man1/file 并且工作正常,但是如何将它存储到资源文件夹中?我以为在我的项目中拖入时保存在资源文件夹中。
    • 您可以将复制文件阶段的目标弹出菜单从“绝对路径”更改为“资源”。
    猜你喜欢
    • 2015-03-23
    • 2021-12-02
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多