本文是依赖HandyJSON
转模型来实现归档
不需要依赖第三方可以看Swift-自动归档
测试代码
@IBAction func btnClick(_ sender: Any) {
let dict = [
"id" : 2,
"name" : "隔壁老王",
"age" : 31,
"phone" : "110"
] as [String : Any]
guard let json = dict.hw_toJSONString() else {
print("出错")
return
}
UserTool.saveUser(json) // 存
guard let user = UserTool.getUser() else { // 取
print("归档失败")
return
}
print("id:\(user.id)\n名字:\(user.name)\n年龄:\(user.age)\n电话:\(user.phone)")
}
// MARK: - 字典转json
extension Dictionary {
public func hw_toJSONString() -> String? {
if (!JSONSerialization.isValidJSONObject(self)) {
print("dict转json失败")
return nil
}
if let newData : Data = try? JSONSerialization.data(withJSONObject: self, options: []) {
let JSONString = NSString(data:newData as Data,encoding: String.Encoding.utf8.rawValue)
return JSONString as String? ?? nil
}
print("dict转json失败")
return nil
}
}
输出内容
id:2
名字:隔壁老王
年龄:31
电话:110
代码实现(注:需依赖第三方HandyJSON)
import HandyJSON
// 在类名前面是使用objcMembers修饰,系统会在自动给这个类的所有方法添加@objc,暴露给OC。
@objcMembers class UserInfo: NSObject, HandyJSON, NSCoding {
var id: Int = 0 // 用户id
var name: String = ""
var phone: String = ""
var age = 0
override required init() { super.init() }
// MARK: - 归档
func encode(with aCoder: NSCoder) {
UserTool.removeUser() // 归档前先删除原来的 避免错误
for name in getAllPropertys() {
let value = self.value(forKey: name)
if (value == nil) { continue }
aCoder.encode(value, forKey: name)
}
}
// MARK: - 解档
internal required init?(coder aDecoder: NSCoder){
super.init()
for name in getAllPropertys() {
let value = aDecoder.decodeObject(forKey: name)
if (value == nil) { continue }
setValue(value, forKeyPath: name)
}
}
// MARK: - 获取属性数组
func getAllPropertys() -> [String] {
var count: UInt32 = 0 // 这个类型可以使用CUnsignedInt,对应Swift中的UInt32
let properties = class_copyPropertyList(self.classForCoder, &count)
var propertyNames: [String] = []
for i in 0..<Int(count) { // Swift中类型是严格检查的,必须转换成同一类型
if let property = properties?[i] { // UnsafeMutablePointer<objc_property_t>是可变指针,因此properties就是类似数组一样,可以通过下标获取
let name = property_getName(property)
// 这里还得转换成字符串
let strName = String(cString: name)
propertyNames.append(strName)
}
}
// 不要忘记释放内存,否则C语言的指针很容易成野指针的
free(properties)
return propertyNames
}
}
class UserTool {
// MARK: - 归档路径设置
static private var Path: String {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
return (path as NSString).appendingPathComponent("\(self).plist")
}
/// 是否登录
static func isLogin() -> Bool {
guard UserTool.getUser() != nil else {return false} // 文件不存在
return true
}
/// 存档
static func saveUser(_ json: String) {
guard let user = UserInfo.deserialize(from: json) else { return } // HandyJSON转模型
NSKeyedArchiver.archiveRootObject(user, toFile: Path)
}
/// 获取用户信息
static func getUser() -> UserInfo? {
let user = NSKeyedUnarchiver.unarchiveObject(withFile: Path) as? UserInfo
return user
}
/// 删档
static func removeUser() {
if FileManager.default.fileExists(atPath: Path) {
try! FileManager.default.removeItem(atPath: Path) // 删除文件
}
}
}