简体   繁体   English

文本文件到字符串数组代码在Playground中有效,但在Xcode项目中无效

[英]Text file to Array of Strings code is working in Playground but not in Xcode project

I have the following code which creates a string array of a text file named num.txt 我有以下代码创建名为num.txt的文本文件的字符串数组

import Foundation
import UIKit

func linesFromResource(fileName: String) throws -> [String] {

    guard let path = NSBundle.mainBundle().pathForResource("num", ofType: "txt") else {
        throw NSError(domain: NSCocoaErrorDomain, code: NSFileNoSuchFileError, userInfo: [ NSFilePathErrorKey : fileName ])
    }
    let content = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
    return content.componentsSeparatedByString("\n")
}

let lines = try linesFromResource("num.txt")
print(lines)

my file num.txt is located in the resource folder of the playground 我的文件num.txt位于游乐场的资源文件夹中

操场

And it works fine and does what is intended, but when I try to do exactly the same thing in a project it gives me this error message: 它工作正常,可以完成预期的工作,但是当我尝试在项目中执行完全相同的操作时,它会显示以下错误消息:

项目

For some reason in the project the file "num.txt" can't be called I've tried creating a Resources folder and putting the file there but it didn't work either, what am I doing wrong? 由于项目中的某些原因,无法调用文件“ num.txt”。我尝试创建一个Resources文件夹并将其放置在该文件夹中,但是它也不起作用,我在做什么错呢?

Please check that num.txt file is added in the Copy Bundle Resources , To check that go here ProjectModule->Build Phases->Copy Bundle Resources . 请检查是否在Copy Bundle Resources添加了num.txt文件,若要检查,请转到ProjectModule->Build Phases->Copy Bundle Resources For getting more idea check image. 为了获得更多的想法检查图像。

在此处输入图片说明

I solved the issue, for some reason when I try to compile a command line application for OSX Copying as Bundle resource doesn't work, I tried to do it as a single view application for iOS and then it worked. 我解决了这个问题,由于某种原因,当我尝试编译OSX的命令行应用程序时,由于捆绑资源不起作用,我尝试将其作为iOS的单视图应用程序进行操作,然后它起作用了。

I was able to make it run as an OSX command line application as well by adding the file as Copy Files instead of Copy Bundle Resources and by selecting resources as destination, I had tried this before but not without first deleting the derived data and clean building as NDoc suggested so I guess both things together did the trick. 通过将文件添加为“复制文件”而不是“复制捆绑资源”,并通过选择资源作为目标,我能够使它作为OSX命令行应用程序运行,我之前曾尝试过此操作,但并非没有先删除派生数据并清理构建正如NDoc所建议的那样,所以我想两者都可以解决问题。

复制文件

linesFromResource("num.txt")更改为linesFromResource("num") ,多余的.txt就是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM