Swift之数据管理(二)-- 编码对象

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

你可能感兴趣的:(Swift之数据管理(二)-- 编码对象)