IOS数据持久化的方式分为三种:
归档(又名序列化),把对象转为字节码,以文件的形式存储到磁盘上;程序运行过程中或者当再次重写打开程序的时候,可以通过解归档(反序列化)还原这些对象。本文主要介绍swift实现iOS数据归档。
func archiveData(){ var path: AnyObject=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] var filePath=path.stringByAppendingPathComponent("data.archive") //归档 var array=["Bill Gates","Steve Jobs"] if(NSKeyedArchiver.archiveRootObject(array, toFile: filePath)){ NSLog("Archive Success") } } func unarchiveData(){ var path: AnyObject=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] var filePath=path.stringByAppendingPathComponent("data.archive") //反归档 var data=NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as NSArray NSLog("%@", data) }
归档自定义数据
var path=NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as NSString var filePath=path.stringByAppendingPathComponent("data.archive") //归档 var data=NSMutableData() var archiver=NSKeyedArchiver(forWritingWithMutableData: data) archiver.encodeObject(["Bill Gates","Steve Jobs"], forKey: "data"); archiver.encodeInt(32, forKey: "age"); archiver.encodeObject("test message", forKey: "tip"); archiver.finishEncoding() data.writeToFile(filePath, atomically: true) //反归档 var unarchiveData=NSData(contentsOfFile: filePath) var unarchiver=NSKeyedUnarchiver(forReadingWithData: unarchiveData!) var decodeData=unarchiver.decodeObjectForKey("data") as NSArray var decodeAge=unarchiver.decodeIntForKey("age") var decodeTip=unarchiver.decodeObjectForKey("tip") as NSString NSLog("data=%@,age=%i,tip=%@",decodeData,decodeAge,decodeTip)