SWIFT如何创buildNSCoding子类并从另一个类中调用它?

我发现NSCoding这黑色的代码,它几乎是想我想要的。 我发现它的链接在下面。 如何在其他类中创build一个NSCoding类和用户? 下面的代码不能工作。 我希望有人能帮助我。

import Foundation import UIKit class User: NSObject, NSCoding { var name: String init(name: String) { self.name = name } required init(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObjectForKey("name") as String } func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "name") } } //new class where I want to set and get the object class MyNewClass: UIViewController { let user = User(name: "Mike") let encodedUser = NSKeyedArchiver.archivedDataWithRootObject(user) let decodedUser = NSKeyedUnarchiver.unarchiveObjectWithData(encodedUser) as User } //http://stackoverflow.com/questions/24589933/nskeyedunarchiver-fails-to-decode-a-custom-object-in-swift 

我从下面的自己的项目中剪切和粘贴。 我已经限制这一个string参数存储到文件。 但是你可以更多的不同types。 你可以把它粘贴到一个swift文件中,并用它作为ViewController加上添加的类来testing。 它演示了使用NSCoding和swift语法来保存和检索对象中的数据。

 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) } }