Piercy
Piercy

Reputation: 493

Fill an array with strings from a txt file

Data.txt contains stuff like this : "Cat" "Dog" "Mouse"

I want to fill an array with strings from that file (dico[0] = "Cat", dico[1] = "Dog", aso).

I found this, How to call Objective-C's NSArray class method from within Swift? and Read and write data from text file, but when I use this code :

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSArray(contentsOfFile: path)

println("\(dico[0])")
println("\(dico.count)")

All I get is "nil" and "0".

I guess data in my file aren't written the way they should be and the code I use isn't right, but I can't figure why.

Moreover, when I use this code, it's OK :

    let bundle = NSBundle.mainBundle()
    let path = bundle.pathForResource("data", ofType: "txt")
    let dico = NSString(contentsOfFile: path)

    println("\(dico)")

The problem is that I don't want dico to be a string, I want it to be an array.

Upvotes: 5

Views: 3725

Answers (3)

Cezar
Cezar

Reputation: 56332

This is not how arrayWithContentsOfFile works.

It expects as its argument the path to a file containing a string representation of an array produced by the writeToFile:atomically: method.

For your purposes, you can use the second approach, complemented by calling componentsSeparatedByString() on your string.

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path).componentsSeparatedByString("\n")

Upvotes: 4

Rafał Sroka
Rafał Sroka

Reputation: 40030

The file you are trying to read must be created using writeToFile:atomically: method. This is what documentation says about it:

aPath - The path to a file containing a representation of an array produced by the writeToFile:atomically: method.

So you have to either create a file using the above-mentioned method or read it as a string and convert it to an array afterwards using for example componentsSeparatedByString: method.

Upvotes: 1

Lance
Lance

Reputation: 9012

NSArray's arrayWithContentsOfFile: initializer isn't meant to be used with regular text file. It's only meant to be used with files that were created using NSArray's writeToFile:atomically:

Assuming you want to split up the words in your text file into an array and assuming each word will be separated by a space, you can do something like this:

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("data", ofType: "txt")
let dico = NSString(contentsOfFile: path)

let components = dico.componentsSeparatedByString(" ")

println("\(components)")

Upvotes: 1

Related Questions