Swiftのデータ管理(二)--符号化対象

1583 ワード

1、studentクラスを定義する
import UIKit

class Student: NSObject, NSCoding {
// MARK: - Properties
var sno: String!
var name: String!
var score: Int!

// MARK: - Init
init(sno: String, name: String, score: Int) {
    self.sno = sno
    self.name = name
    self.score = score
}

// MARK: - NSCoding

//  
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(sno, forKey: "sno")
    aCoder.encodeObject(name, forKey: "name")
    aCoder.encodeInteger(score, forKey: "score")
}

//  
required init?(coder aDecoder: NSCoder) {
    sno = aDecoder.decodeObjectForKey("sno") as! String
    name = aDecoder.decodeObjectForKey("name") as! String
    score = aDecoder.decodeIntegerForKey("score")
}
}

2、主クラス呼び出し
import UIKit

class ViewController: UIViewController {
// Documents 
lazy var documentsPath: String = {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    return paths.first!
}()

override func viewDidLoad() {
    super.viewDidLoad()
    
    
    //  
    
    //  
    let student = Student(sno: "1101", name: "maizixueyuan", score: 99)
    
    //  
    let path = "\(documentsPath)/student.archive"
    
    //  
    NSKeyedArchiver.archiveRootObject(student, toFile: path)
    
    
    //  
    let object = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! Student
    print("\(object.sno), \(object.name), \(object.score)")
    
    
    //  
    print("\(NSHomeDirectory())")
}
}