专业java、php、iOS、C++、网页设计、平面设计、网络营销、游戏开发、前端与移动开发培训机构

清除本地缓存

  • 用户微博数据缓存到本地数据库,随着用户的使用时间越来越长,数据库里面的数据会越来越多,数据库占用的磁盘空间越来越大.定时清理早期的数据.

  • Navicat添加createTime字段,设置默认值

  • 确定通过createTime可以查询数据

  • 修改数据表脚本

    CREATE TABLE "T_Status" (
       "statusid" INTEGER NOT NULL,
       "status" TEXT,
       "userid" INTEGER,
       "createTime" TEXT DEFAULT (datetime('now', 'localtime')),
      PRIMARY KEY("statusid")
    )
    
  • 定义缓存时间 常量

    /// 数据缓存时间
    private let cacheDataTime: NSTimeInterval = 60 // 7 * 24 * 60 * 60
    
  • 清理缓存函数

    /**
    清除超过缓存时间的数据
    每当程序退出到后台,检测过时的缓存数据,并清除
    */
    func clearCacheData() {
      // 计算过期数据的日期
      let clearDate = Date(timeIntervalSinceNow: -cacheDataTime)
    
      // 转成和sqlite一样格式的时间
      let df = DateFormatter()
      df.locale = Locale(identifier: "en")
      df.dateFormat = "yyyy-MM-dd HH:mm:ss"
      let dateString = df.string(from: clearDate)
    
      print("clearDate: \(dateString)")
    
      // 确定sql
      let sql = "DELETE FROM T_Status WHERE createTime < '\(dateString)';"
    
      // 删除过期的缓存数据
      HMSQLiteManager.shared.dbQueue.inTransaction { (db, rollback) -> Void in
          if db.executeUpdate(sql) {
              print("删除缓存成功")
          }
      }
    }
    
  • AppDelegate 里调用 clearCacheData
    func applicationDidEnterBackground(_ application: UIApplication) {
      // 应用退到后台,清除数据
      HMStatusDAL.shared.clearCacheData()
    }
    

results matching ""

    No results matching ""