您的位置:首页 > 移动开发 > Swift

swift数据持久化--归档

2016-03-10 00:36 726 查看
在数据存储上比较常用,下面给大家简单介绍一下归档:

一般情况下我们先从网络上获取json数据,然后简历数据模型,最后将数据模型存储,但是归档不是所有的数据类型都可以存储,归档存储的类型包括:NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary五种类型,如果不能归档,我们可以尝试转化为这五种中的任何一种再进行存储

//这里要遵守nscoding协议
class UserData: NSObject , NSCoding {

var expires_Date:NSDate?
var uid:String?
var avatar_large: String?
var screen_name: String?

// 1.0用字典初始化模型
init(dict:[String:AnyObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
//如果字典中又缺少值的情况不会报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
print(key)
}

//MARK: NACODING协议
//2.0 将对象写入到文件中
func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeObject(access_token, forKey: "access_token")
aCoder.encodeObject(expires_in, forKey: "expires_in")
aCoder.encodeObject(uid, forKey: "uid")
aCoder.encodeObject(expires_Date, forKey: "expires_Date")
}
//3.0 从文件中读取对象
required init?(coder aDecoder: NSCoder)
{
access_token = aDecoder.decodeObjectForKey("access_token") as? String
expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
uid = aDecoder.decodeObjectForKey("uid") as? String
expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
}

//下面定义两个方法供外部使用

//4.0 保存授权模型
func saveAccount()
{
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
let filePath = (path as NSString).stringByAppendingPathComponent("user.plist")
print("filePath \(filePath)")
NSKeyedArchiver.archiveRootObject(self, toFile: filePath)
}

//5.0 加载授权模型
class func loadAccount() -> UserAccount? {
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
let filePath = (path as NSString).stringByAppendingPathComponent("user.plist")
print("filePath \(filePath)")

let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? UserAccount
return account
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息