使用
使用归档和解档来保存用户数据
归档:把当前对象保存到磁盘前,将对象编码成二进制数据
解档:从磁盘加载二进制文件,转换成对象调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import UIKit
class UserAccount: NSObject, NSCoding { var userName: String? var userToken: String? var expiresDate: NSDate? var userDevices: String? func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(userName, forKey: "userName") aCoder.encodeObject(userToken, forKey: "userToken") aCoder.encodeObject(expiresDate, forKey: "expiresDate") aCoder.encodeObject(userDevices, forKey: "userDevices") } required init?(coder aDecoder: NSCoder) { userName = aDecoder.decodeObjectForKey("userName") as? String userToken = aDecoder.decodeObjectForKey("userToken") as? String expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? String userDevices = aDecoder.decodeObjectForKey("userDevices") as? String } func saveUserAccount() { var path = NSSearchPathForDirctoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! path = (path as NSString).stringByAppendingPathComponent("account.plist") NSKeyedArchiver.archiveRootObject(self, toFile: path) } }
|
一般归档不需要保存成plist
,但开发中必须确认数据是否正确的保存下来了,为方便查看保存成plist
格式
使用视图模型进行解裆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import Foundation class UserAccountViewModel { var account: UserAccount? var userLogin: Bool { return account?.userToken != nil && !isExpired } private var accountPath: String { let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! return (path as NSString).stringByAppendingPathComponent("account.plist") } private var isExpired: Bool { if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending { return false } return true } init() { account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount if isExpired { print("已经过期") account = nil } } }
|