1

I am trying to add persistance to my application, so i have to read and write to a file

This is the code i use to read:

let path = NSBundle.mainBundle().pathForResource("Data", ofType: "txt")
var text = String(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!

and this is the line I use to write

text.writeToFile(path!, atomically: false, encoding: NSUTF8StringEncoding, error: nil)

Here happens something strange,there is no Data.txt file in my project folder but it works.Why?

To solve this i deleted some folders,created a Data.txt file in the project folder and the app work fine but i cannot see the data stored in the txt file,why?And if i delete the file the app doesn't show errors and continues to work even if i moved to thrash the file.How is it possible?How can I edit or delete this file before it's loaded in the application?

Another issue I have is that i would like to use an array instead of a big string,the array should be like this

var array = [(number:Int(),name:String(),date:String())]

the txt file has the following structure number\tname\tdate\nnumber\tname\tdate and so on

I don't know how to split the different lines of the file into an array and the 3 elements of the line into an element of the array using "\n" as separator for the elements and \t to separate the Int and the two Strings

And I don't know how to save the array in the txt file and reload it,do I have to use some for cycle or some while or there is some function specific for my case?

Thanks

1 Answer 1

3

You won't be able to save a tuple using NSUserDefaults, so I think you should use a subarray to group your data before storing it:

class Load {
    class func array(key:String) -> [AnyObject]! {
        return NSUserDefaults.standardUserDefaults().arrayForKey(key)
    }
}
class Save {
    class func array(key:String, _ value:[AnyObject]){
        NSUserDefaults.standardUserDefaults().setObject(value, forKey: key)
    }

}
var number = 15
var name = "John"
var date = NSDate()

var myArray:[[AnyObject]] = []

myArray.append([number,name,date])

Save.array("myArray", myArray)

number = 16
name = "Jane"
date = NSDate().dateByAddingTimeInterval(60*60*24)

myArray.append([number,name,date])
Save.array("myArray", myArray)


let loadedArray = Load.array("myArray")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.