I found this black of code on NSCoding and it almost does want I want it to. the link for where I found it is below. How do I create a NSCoding class and user in in other c
I'm cutting and pasting from my own project below. I have limited this to one string parameter to store to file. But you can more of different types. You can paste this into a single swift file and use it as the ViewController plus added classes to test. It demonstrates using NSCoding with swift syntax to save and retrieve data in an object.
import UIKit
import Foundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var instanceData = Data()
instanceData.name = "testName"
ArchiveData().saveData(nameData: instanceData)
let retrievedData = ArchiveData().retrieveData() as Data
println(retrievedData.name)
}
}
class Data: NSObject {
var name: String = ""
func encodeWithCoder(aCoder: NSCoder!) {
aCoder.encodeObject(name, forKey: "name")
}
init(coder aDecoder: NSCoder!) {
name = aDecoder.decodeObjectForKey("name") as String
}
override init() {
}
}
class ArchiveData:NSObject {
var documentDirectories:NSArray = []
var documentDirectory:String = ""
var path:String = ""
func saveData(#nameData: Data) {
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("data.archive")
if NSKeyedArchiver.archiveRootObject(nameData, toFile: path) {
//println("Success writing to file!")
} else {
println("Unable to write to file!")
}
}
func retrieveData() -> NSObject {
var dataToRetrieve = Data()
documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
documentDirectory = documentDirectories.objectAtIndex(0) as String
path = documentDirectory.stringByAppendingPathComponent("data.archive")
if let dataToRetrieve2 = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? Data {
dataToRetrieve = dataToRetrieve2 as Data
}
return(dataToRetrieve)
}
}