1. 程式人生 > >[Xcode10 實際操作]七、檔案與資料-(12)資料持久化儲存框架CoreData的使用:查詢CoreData中的資料

[Xcode10 實際操作]七、檔案與資料-(12)資料持久化儲存框架CoreData的使用:查詢CoreData中的資料

本文將演示如何查詢資料持久化物件。

在專案導航區,開啟檢視控制器的程式碼檔案【ViewController.swift】

 1 import UIKit
 2 //引入資料持久化儲存框架【CoreData】
 3 import CoreData
 4 
 5 class ViewController: UIViewController {
 6 
 7     override func viewDidLoad() {
 8         super.viewDidLoad()
 9         // Do any additional setup after loading the view, typically from a nib.
10 11 self.addUser() 12 13 //獲得當前程式的應用代理 14 let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate 15 //通過應用代理物件,獲得管理物件上下文 16 let managedObjectContext = appDelegate.persistentContainer.viewContext 17 18 //
通過管理物件上下文,根據實體的名稱,獲得實體物件 19 let entity = NSEntityDescription.entity(forEntityName: "User", 20 in: managedObjectContext) 21 22 //建立一個數據提取請求物件 23 let request = NSFetchRequest<User>(entityName: "User") 24 //
設定提取資料的偏移值 25 request.fetchOffset = 0 26 //設定提取資料的數量 27 request.fetchLimit = 10 28 //繼續設定需要提取資料的實體物件 29 request.entity = entity 30 31 //然後建立一個謂詞物件,設定提取資料的查詢條件。 32 //謂詞被用來指定資料被獲取,或者過濾的方式 33 let predicate = NSPredicate(format: "userName= 'John' ", "") 34 //設定資料提取請求物件的謂詞屬性 35 request.predicate = predicate 36 37 //新增一條異常捕捉語句,用於執行資料的查詢操作 38 do{ 39 //使用try語句,執行管理物件上下文的資料提取操作, 40 //並把提取的結果,儲存在一個數組中 41 let items = try managedObjectContext.fetch(request) 42 //建立一個迴圈語句,對提取結果進行遍歷操作 43 for user:User in items 44 { 45 //在控制檯列印輸出相關日誌 46 print("userName=\(user.userName!)") 47 print("password=\(user.password!)") 48 } 49 50 } 51 catch{ 52 print("獲取資料失敗。") 53 } 54 } 55 56 func addUser() 57 { 58 //獲得當前程式的應用代理 59 let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate 60 //通過應用代理物件,獲得管理物件上下文 61 let managedObjectContext = appDelegate.persistentContainer.viewContext 62 63 //通過管理物件上下文,插入一條實體資料 64 let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", 65 into: managedObjectContext) as! User 66 67 //設定實體的使用者名稱屬性的內容 68 newUser.userName = "John" 69 //設定實體的密碼屬性的內容 70 newUser.password = "123456" 71 72 //新增一條異常捕捉語句,用於執行資料的插入操作 73 do 74 { 75 //使用try語句,執行管理物件上下文的儲存操作,插入實體物件 76 try managedObjectContext.save() 77 //在控制檯列印輸出日誌 78 print("Success to save data.") 79 } 80 catch 81 { 82 print("Failed to save data.") 83 } 84 } 85 override func didReceiveMemoryWarning() { 86 super.didReceiveMemoryWarning() 87 // Dispose of any resources that can be recreated. 88 } 89 }