目錄:[Swift]Xcode實際操做html
本文將演示如何修改數據持久化對象。swift
在項目導航區,打開視圖控制器的代碼文件【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 //得到當前程序的應用代理對象 12 let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate 13 //經過應用代理對象,得到管理對象上下文 14 let managedObjectContext = appDelegate.persistentContainer.viewContext 15 16 //經過管理對象上下文,根據實體的名稱,得到實體對象 17 let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: "User", 18 in: managedObjectContext) 19 20 //建立一個數據提取請求對象 21 let request:NSFetchRequest = NSFetchRequest<User>(entityName: "User") 22 //設置提取數據的偏移值 23 request.fetchOffset = 0 24 //設置提取數據的數量 25 request.fetchLimit = 10 26 //設置須要提取數據的實體對象 27 request.entity = entity 28 29 //添加一條異常捕捉語句,用於執行數據的查詢和編輯操做 30 do 31 { 32 //使用try語句,執行管理對象上下文的數據提取操做, 33 //並把提取的結果,存儲在一個數組中 34 let results:[AnyObject]? = try managedObjectContext.fetch(request) 35 //建立一個循環語句,對提取結果進行遍歷操做 36 for user:User in results as! [User] 37 { 38 //同時在循環語句中,更改實體的用戶名屬性 39 user.userName = "Peter" 40 } 41 42 //執行管理對象上下文的數據存儲操做,保存編輯以後的結果 43 try managedObjectContext.save() 44 45 //使用try語句,執行管理對象上下文的數據提取操做, 46 //從新提取編輯後的數據 47 let results2:[AnyObject]? = try managedObjectContext.fetch(request) 48 //建立一個循環語句,對新的提取結果進行遍歷操做 49 for user:User in results2 as! [User] 50 { 51 //在控制檯打印輸出相關日誌 52 print("userName=\(user.userName!)") 53 print("password=\(user.password!)") 54 } 55 } 56 catch 57 { 58 print("Failed to modify data.") 59 } 60 } 61 62 override func didReceiveMemoryWarning() { 63 super.didReceiveMemoryWarning() 64 // Dispose of any resources that can be recreated. 65 } 66 }