【问题标题】:Loading text data in an iPhone application在 iPhone 应用程序中加载文本数据
【发布时间】:2011-01-03 19:02:30
【问题描述】:

我创建了一个 iPhone 应用程序,我希望能够使用该应用程序加载一批数据,但不将所有数据存储在 .h 或 .m 文件中。

有没有办法将文本文件作为资源附加到应用程序中,然后将该文本文件加载到 iPhone 应用程序中的 NSString 中。

我希望在编译时将此文本数据文件作为 iPhone 应用程序的一部分包含在内,但要在运行时访问数据。

谢谢!

【问题讨论】:

    标签: iphone cocoa-touch ios4


    【解决方案1】:

    当然,这很容易。只需将您的 .txt 文件添加到您的项目中(将它们拖到文件树中)。要访问它们,您需要先获取路径:

    NSString *path = [[NSBundle mainBundle] pathForResource: @"filename" ofType: @"txt"];
    

    然后加载字符串:

    NSError *error = nil;
    NSString *fileData = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: &error];
    

    【讨论】:

    • 刚刚意识到我提供的链接使用了不推荐使用的方法,哎呀!所以 +1 是最新的!
    • 完美。这正是我想要的。谢谢!
    【解决方案2】:

    下面是一个这样做的例子: http://iphoneincubator.com/blog/data-management/how-to-read-a-file-from-your-application-bundle

    以上链接的相关代码:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"important" ofType:@"txt"];  
    if (filePath) {  
      NSString *myText = [NSString stringWithContentsOfFile:filePath];  
      if (myText) {  
        textView.text= myText;  
      }  
    }  
    

    【讨论】:

    • 请务必查看我对@Ben Gottlieb 的回答的评论,我会在此处留下我的答案,因为我认为该链接仍然有用,但您需要使用@Ben Gottlieb 的 stringWithContentsOfFile 方法版本使用最新版本的 SDK。
    猜你喜欢
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多