歡迎加入QQ討論群258996829

Swift 緩存庫 Cache

發(fā)布時間:2017-07-01 21:32  回復(fù):0  查看:9652  感興趣:121  贊:3   最后回復(fù):2017-07-01 21:32  
Cache是一個Swift緩存庫,可以將各種對象以key存儲到磁盤,同時可以設(shè)置存儲的失效期。 還可以設(shè)置數(shù)據(jù)保護確保數(shù)據(jù)的安全性。
同步API
let cache = HybridCache(name: "Mix")
// Add object to cache
try cache.addObject("This is a string", forKey: "string", expiry: .never)
try cache.addObject(JSON.dictionary(["key": "value"]), "json")
try cache.addObject(UIImage(named: "image.png"), forKey: "image")
try cache.addObject(Data(bytes: [UInt8](repeating: 0, count: 10)), forKey: "data")

// Get object from cache
let string: String? = cache.object(forKey: "string") // "This is a string"
let json: JSON? = cache.object(forKey: "json")
let image: UIImage? = cache.object(forKey: "image")
let data: Data? = cache.object(forKey: "data")

// Get object with expiry date
let entry: CacheEntry<String>? = cache.cacheEntry(forKey: "string")
print(entry?.object) // Prints "This is a string"
print(entry?.expiry.date) // Prints expiry date

// Get total cache size on the disk
let size = try cache.totalDiskSize()

// Remove object from cache
try cache.removeObject(forKey: "data")

// Clear cache
// Pass `true` to keep the existing disk cache directory after removing
// its contents. The default value for `keepingRootDirectory` is `false`.
try cache.clear(keepingRootDirectory: true)

// Clear expired objects
try cache.clearExpired()
異步API
// Add object to cache
cache.async.addObject("This is a string", forKey: "string") { error in
  print(error)
}

// Get object from cache
cache.async.object(forKey: "string") { (string: String?) in
  print(string) // Prints "This is a string"
}

// Get object with expiry date
cache.async.cacheEntry(forKey: "string") { (entry: CacheEntry<String>?) in
  print(entry?.object) // Prints "This is a string"
  print(entry?.expiry.date) // Prints expiry date
}

// Remove object from cache
cache.async.removeObject(forKey: "string") { error in
  print(error)
}

// Clear cache
cache.async.clear() { error in
  print(error)
}

// Clear expired objects
cache.async.clearExpired() { error in
  print(error)
}

相關(guān)開源代碼

您還未登錄,請先登錄

熱門帖子

最新帖子

?