在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
IOS数据持久化的方式分为三种:
归档(又名序列化),把对象转为字节码,以文件的形式存储到磁盘上;程序运行过程中或者当再次重写打开程序的时候,可以通过解归档(反序列化)还原这些对象。本文主要介绍swift实现iOS数据归档。
归档Foundation框架对象
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)
小结:
|
请发表评论