Swift中數(shù)據(jù)存儲(二)之CoreData初探

一,Core Data介紹

① Core Data是iOS5之后才出現(xiàn)的一個數(shù)據(jù)持久化存儲框架,它提供了對象-關(guān)系映射(ORM)的功能,即能夠?qū)ο筠D(zhuǎn)化成數(shù)據(jù),也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成對象。
② 雖然其底層也是由類似于SQL的技術(shù)來實(shí)現(xiàn),但我們不需要編寫任何SQL語句,有點(diǎn)像Java開發(fā)中的Hibernate持久化框架
③ Core Data數(shù)據(jù)最終的存儲類型可以是:SQLite數(shù)據(jù)庫,XML,二進(jìn)制,內(nèi)存里,或自定義數(shù)據(jù)類型。
④ 與SQLite區(qū)別:只能取出整個實(shí)體記錄,然后分解,之后才能得到實(shí)體的某個屬性。

二,Core Data的使用準(zhǔn)備 - 數(shù)據(jù)模型和實(shí)體類的創(chuàng)建
① 創(chuàng)建項(xiàng)目的時候,勾選“Use Core Data”。完畢后在AppDelegate 中,會生成相關(guān)代碼。

項(xiàng)目文件創(chuàng)建.png

② 打開項(xiàng)目中的 xcdatamodeld
** 文件,在右邊的數(shù)據(jù)模型編輯器的底部工具欄點(diǎn)擊 Add Entity
** 添加實(shí)體,實(shí)體名稱設(shè)置為"User"。
同時在屬性欄中對實(shí)體命名進(jìn)行修改,并在 Attribute
** 欄目中添加 id
username
password
** 三個屬性
文件.png

③ 點(diǎn)擊上圖中
Editor Style
可以查看實(shí)體的關(guān)系圖,如下圖
視圖關(guān)系圖.png

④ 要為每一個實(shí)體生成一個對應(yīng)的 創(chuàng)建NSManagedObject 子類,通過類的成員屬性來訪問和獲取數(shù)據(jù)。選中
.xcdatamodeld
文件,點(diǎn)擊Editor里面的Create NSManagerObject SubClass創(chuàng)建類,如下圖:
創(chuàng)建NSManagedObject子類.png

⑤ 創(chuàng)建完成后,項(xiàng)目中會多出** User+CoreDataProperties.swiftUser.Swift**文件

三 Core Data的使用
首先創(chuàng)建一個CoredData的工具類,用來操作CoreData,并導(dǎo)入import CoreData
① 插入數(shù)據(jù),并保存

// MARK:- 插入(保存)數(shù)據(jù)操作
  internal func insetData(){
    
    // 獲取管理的數(shù)據(jù)上下文  對象
    let app = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = app.managedObjectContext
    
    // 創(chuàng)建User對象
    /**
     insertNewObjectForEntityForName 里面
     <#T##entityName: String##String#> 實(shí)體名稱
     <#T##NSManagedObjectContext#> 上下文
     */
    let user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as! User
    
    // 對象賦值
    user.id = 1
    user.username = "RookieYX"
    user.password = "1234"
    
    // 保存
    do{
      try context.save()
      print("保存成功")
    }
    catch{
      fatalError("無法保存 \\\\(error)")
    }
  }
  

② 查詢數(shù)據(jù)操作

// MARK:- 查詢數(shù)據(jù)操作
  internal func searchData(){
    
    // 獲取管理的數(shù)據(jù)上下文  對象
    let app = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = app.managedObjectContext
    
    // 聲明數(shù)據(jù)的請求
    let fetchRequest:NSFetchRequest =  NSFetchRequest()
    fetchRequest.fetchLimit = 10  // 限定查詢結(jié)果的數(shù)量
    fetchRequest.fetchOffset = 0  // 查詢的偏移量
    
    // 聲明一個實(shí)體結(jié)構(gòu)
    let entity:NSEntityDescription? = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
    // 設(shè)置數(shù)據(jù)請求的實(shí)體結(jié)構(gòu)
    fetchRequest.entity = entity
    
    // 設(shè)置查詢條件
    let predicate = NSPredicate(format: "id = '1'", "")
    fetchRequest.predicate = predicate
    
    // 查詢操作
    do{
      let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
      // 遍歷查詢的結(jié)果
      for info:User in fetchedObjects as! [User] {
        print("id=\\\\(info.id)")
        print("username=\\\\(info.username)")
        print("password=\\\\(info.password)")
      }
    }
    catch {
      fatalError("不能保存:\\\\(error)")
    }
  }

③ 修改數(shù)據(jù)操作

internal func updateData(){
    // 獲取管理的數(shù)據(jù)上下文  對象
    let app = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = app.managedObjectContext
    
    // 聲明數(shù)據(jù)的請求
    let fetchRequest:NSFetchRequest =  NSFetchRequest()
    fetchRequest.fetchLimit = 10  // 限定查詢結(jié)果的數(shù)量
    fetchRequest.fetchOffset = 0  // 查詢的偏移量
    
    // 聲明一個實(shí)體結(jié)構(gòu)
    let entity:NSEntityDescription? = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
    // 設(shè)置數(shù)據(jù)請求的實(shí)體結(jié)構(gòu)
    fetchRequest.entity = entity
    
    // 設(shè)置查詢條件
    let predicate = NSPredicate(format: "id = '1'", "")
    fetchRequest.predicate = predicate
    
    // 查詢操作
    do{
      let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
      // 遍歷查詢的結(jié)果
      for info:User in fetchedObjects as! [User] {
        //修改密碼
        info.password = "abcd"
        //重新保存
        try context.save()
      }
    }
    catch {
      fatalError("不能保存:\\\\(error)")
    }
  }
  

④ 刪除數(shù)據(jù)操作

// MARK:- 刪除數(shù)據(jù)操作
  internal func delecteData(){
    // 獲取管理的數(shù)據(jù)上下文  對象
    let app = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = app.managedObjectContext
    
    // 聲明數(shù)據(jù)的請求
    let fetchRequest:NSFetchRequest =  NSFetchRequest()
    fetchRequest.fetchLimit = 10  // 限定查詢結(jié)果的數(shù)量
    fetchRequest.fetchOffset = 0  // 查詢的偏移量
    
    // 聲明一個實(shí)體結(jié)構(gòu)
    let entity:NSEntityDescription? = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
    // 設(shè)置數(shù)據(jù)請求的實(shí)體結(jié)構(gòu)
    fetchRequest.entity = entity
    
    // 設(shè)置查詢條件
    let predicate = NSPredicate(format: "id = '1'", "")
    fetchRequest.predicate = predicate
    
    // 查詢操作
    do{
      let fetchedObjects:[AnyObject]? = try context.executeFetchRequest(fetchRequest)
      // 遍歷查詢的結(jié)果
      for info:User in fetchedObjects as! [User] {
        //刪除對象
        context.deleteObject(info)
      }
      // 重新保存 - 更新到數(shù)據(jù)庫中
      try context.save()
    }
    catch {
      fatalError("不能保存:\\\\(error)")
    }
  }

** 四 在ViewController中使用我們的CoreData工具類**

    let tool = CoreDataTool()
    // 插入數(shù)據(jù)
    tool.insetData()
    // 查詢
    tool.searchData()
    // 更新修改
    tool.updateData()
    // 刪除
    tool.delecteData()

學(xué)習(xí)NSUserDefaults/ NSKeyedArchiver/ write儲存,可以看之前的文章

Swift數(shù)據(jù)存儲(一)

Swift數(shù)據(jù)存儲SQLite

之后將持續(xù)更新CoreData的深入學(xué)習(xí)知識,想要學(xué)習(xí)的同學(xué)可以繼續(xù)關(guān)注

本文參考:www.mamicode.com/info-detail-1061698.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容