欢迎加入QQ讨论群258996829

Swift 缓存库 Cache

发布时间:2017-07-01 21:32  回复:0  查看:9752  感兴趣:121  赞:3   最后回复:2017-07-01 21:32  
Cache是一个Swift缓存库,可以将各种对象以key存储到磁盘,同时可以设置存储的失效期。 还可以设置数据保护确保数据的安全性。
同步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)
}

相关开源代码

您还未登录,请先登录

热门帖子

最新帖子