我們平常比較常用的模型緩存一般都是通過歸檔解檔實(shí)現(xiàn)的荷愕,詳情請參考我之前寫的一篇文章歸檔解檔峡迷。
今天我介紹的一種新的緩存方式:模型轉(zhuǎn)JSON字符串緩存
直接上代碼:
import ObjectMapper
extension Mappable {
private static func cacheDirectory(isCreateFile:Bool, name:String) throws -> URL {
let url:URL = DHFileManager.documentDirectory().appendingPathComponent("\(name)_Data")
if isCreateFile && !FileManager.default.fileExists(atPath: url.path) {
let attr: [FileAttributeKey: Any] = [FileAttributeKey(rawValue: FileAttributeKey.protectionKey.rawValue): FileProtectionType.complete]
let ret = FileManager.default.createFile(atPath: url.path, contents: nil, attributes: attr)
if ret {
return url
} else {
throw NSError.init(domain: "fail", code: 10001, userInfo: ["fail" : "文件創(chuàng)建失敗"])
}
}
return url
}
static func getCacheModel<T:Mappable>(class:T.Type) -> T? {
do {
let jsonString = try String(contentsOf: cacheDirectory(isCreateFile: false, name: "\(self)"))
return Mapper<T>().map(JSONString: jsonString) ?? nil
} catch {
return nil
}
}
func writeCacheModel() -> Bool {
do {
let modelType = type(of: self)
let url = try Self.cacheDirectory(isCreateFile: true, name: "\(modelType)")
let string = self.toJSONString() ?? ""
try string.write(to: url, atomically: true, encoding: String.Encoding.utf8)
} catch {
return false
}
return true
}
static func removeCacheModel() -> Bool {
do {
let url = try Self.cacheDirectory(isCreateFile: true, name: "\(self)")
try FileManager.default.removeItem(at: url)
} catch {
return false
}
return true
}
}
獲取文件路徑的方法:
class DHFileManager {
class func documentDirectory() -> URL {
let URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
return URL
}
class func libraryDirectory() -> URL {
let URL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first!
return URL
}
class func cachesDirectory() -> URL {
let URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
return URL
}
}
調(diào)用方法也很簡單:
//注意需要緩存的model需要實(shí)現(xiàn)Mappable協(xié)議
let model = TestModel()
//寫緩存
model.writeCacheModel()
//讀緩存
let model = TestModel.getCacheModel(TestModel.self)
//清緩存
TestModel.removeCacheModel()