创建一个学生类,首先归档保存学生信息,然后再解档读取数据
import UIKit
class Student:NSObject, NSCoding{
var sno:String!
var name:String!
var score:Int!
init(sno:String,name:String,score:Int) {
self.sno=sno
self.name=name
self.score=score
}
//编码的时候调用这个方法
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")
}
}
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 students=Student(sno:"1101",name:"刀冲",score:59)
//构造路径
let path="(documentsPath)/student.archive"
//归档对象
NSKeyedArchiver.archiveRootObject(students, toFile:path)
//解档操作
let object=NSKeyedUnarchiver.unarchiveObjectWithFile(path) as! Student
print("(object.sno), (object.name), (object.score)")
//检查文件
print("(NSHomeDirectory())")
}
}