日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Swift实现CoreData存储数据

發布時間:2025/4/16 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Swift实现CoreData存储数据 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

之前寫過一篇介紹iOS數據存儲方法的文章,包含:FMDB,SQLite3 ,Core Data,Plist,偏好設置,歸檔。 鏈接:www.jianshu.com/p/e88880be7…

本文則是介紹Swift中CoreData的基本使用。
文中示例代碼GitHub地址:Demo

目錄

一、 圖形化創建模型
二、 手動創建模型并實現AppDelegate中的代碼
三、 創建并實現CoreDataManager

一、圖形化創建模型(這一小節的內容我的另一篇文中也有,如已經熟悉,或想要直接手動創建模型,可以直接看第二小節正式進入Swift)

創建項目的時候,勾選下圖中的Use Core Data選項,工程中會自動創建一個數據模型文件。當然,你也可以在開發中自己手動創建。

下圖就是自動創建出來的文件

如果沒有勾選,也可以在這里手動創建。

點擊Add Entity之后,相當一張數據表。表的名稱自己在上方定義,注意首字母要大寫。 在界面中還可以為數據實體添加屬性和關聯屬性。

Core Data屬性支持的數據類型如下

編譯之后,Xcode會自動生成Person的實體代碼文件,并且文件不會顯示在工程中,如果下圖中右側Codegen選擇Manual/None,則Xcode就不會自動生成代碼,我們可以自己手動生成。

  • 手動生成實體類代碼,選中CoreDataTest.xcdatamodeld文件,然后在Mac菜單欄中選擇Editor,如下圖所示。一路Next就可以了。
  • 如果沒有選擇Manual/None,依然進行手動創建的話,則會與系統自動創建的文件發生沖突,這點需要注意。
  • 你也可以不要選擇Manual/None,直接使用系統創建好的NSManagedObject,同樣會有4個文件,只是在工程中是看不到的。

Swift中手動創建出來的是這樣2個文件

還要注意編程語言的選擇,Swift或OC

二、手動創建模型并實現AppDelegate中的代碼

講道理,這一節應該是Core Data堆棧的介紹與使用,不過由于之前的文章中已經有了,這里就不啰嗦了,我們直接上圖和代碼。

  • 如下圖所示,創建模型,我這里直接創建一個命名為Model的模型。

  • 創建Person表,兩個屬性name和age,注意右側的Codegen我們這里選擇Class Definition,然后直接Command+B編譯代碼,Xcode會自動幫我們生成Person+CoreDataClass.swift和Person+CoreDataProperties.swift文件

  • 配置AppDelegate中的代碼,首先導入CoreData頭文件,然后懶加載NSManagedObjectModel
  • 注意modelURL中填寫的是模型文件的名字,并且后綴填寫momd

    import CoreDatalazy var managedObjectModel: NSManagedObjectModel = {let modelURL = Bundle.main.url(forResource: "Model", withExtension: "momd")let managedObjectModel = NSManagedObjectModel.init(contentsOf: modelURL!)return managedObjectModel!}() 復制代碼
  • 懶加載持久化存儲協調器NSPersistentStoreCoordinator
    • sqliteURL是sqlite文件的路徑
    • documentDir是后面加載好了的Document路徑
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {let persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: managedObjectModel)let sqliteURL = documentDir.appendingPathComponent("Model.sqlite")let options = [NSMigratePersistentStoresAutomaticallyOption : true, NSInferMappingModelAutomaticallyOption : true]var failureReason = "There was an error creating or loading the application's saved data."do {try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: sqliteURL, options: options)} catch {// Report any error we got.var dict = [String: Any]()dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as Any?dict[NSLocalizedFailureReasonErrorKey] = failureReason as Any?dict[NSUnderlyingErrorKey] = error as NSErrorlet wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 6666, userInfo: dict)print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")abort()}return persistentStoreCoordinator}()lazy var documentDir: URL = {let documentDir = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).firstreturn documentDir!}() 復制代碼
  • 懶加載NSManagedObjectContext
  • lazy var context: NSManagedObjectContext = {let context = NSManagedObjectContext.init(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)context.persistentStoreCoordinator = persistentStoreCoordinatorreturn context}() 復制代碼

    三、創建并實現CoreDataManager

    我一般是把數據存儲方法封裝到一個CoreDataManager中,這樣在以后的使用中比較方便。當然,你也可以根據自己的需求靈活運用。

  • 創建一個繼承自NSObject的CoreDataManager.swfit文件,并且import CoreData

  • 實現CoreDataManager的單例,并且拿到AppDelegate中剛才懶加載的NSManagedObjectContext

  • swift中創建單例比較方便,直接static let shared = CoreDataManager()

    // 單例static let shared = CoreDataManager()// 拿到AppDelegate中創建好了的NSManagedObjectContextlazy var context: NSManagedObjectContext = {let context = ((UIApplication.shared.delegate) as! AppDelegate).contextreturn context}() 復制代碼
  • 實現更新數據的方法
  • 除了查詢數據,其余對數據進行增刪改的時候,都別忘記調用這個方法,只有這個方法執行ok,才算增刪改完成。

    // 更新數據private func saveContext() {do {try context.save()} catch {let nserror = error as NSErrorfatalError("Unresolved error \(nserror), \(nserror.userInfo)")}} 復制代碼
  • 增加數據(保存數據)
    • 首先運用NSEntityDescription創建出person
    • 然后為person賦值,最終調用saveContext()方法保存數據
    // 增加數據func savePersonWith(name: String, age: Int16) {let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) as! Personperson.name = nameperson.age = agesaveContext()} 復制代碼
  • 獲取所有數據
    • 如果是通過系統自動生成的CoreData文件,Person會自帶一個fetchRequest()的方法,我們可以直接通過Person.fetchRequest()的方式拿到person的NSFetchRequest對象
    • 然后通過context的fetch(fetchRequest)方法拿到數據數組
    // 獲取所有數據func getAllPerson() -> [Person] {let fetchRequest: NSFetchRequest = Person.fetchRequest()do {let result = try context.fetch(fetchRequest)return result} catch {fatalError();}} 復制代碼
  • 獲取特定條件的數據
    • 可以利用NSPredicate來過濾出符合一定條件的數據
    • 而NSFetchRequest中有predicate這樣一個屬性
    // 根據姓名獲取數據func getPersonWith(name: String) -> [Person] {let fetchRequest: NSFetchRequest = Person.fetchRequest()fetchRequest.predicate = NSPredicate(format: "name == %@", name)do {let result: [Person] = try context.fetch(fetchRequest)return result} catch {fatalError();}} 復制代碼
  • 修改數據
    • 首先獲取到想要修改的數據
    • 然后循環修改就可以了
    • 最后別忘記save
    // 根據姓名修改數據func changePersonWith(name: String, newName: String, newAge: Int16) {let fetchRequest: NSFetchRequest = Person.fetchRequest()fetchRequest.predicate = NSPredicate(format: "name == %@", name)do {// 拿到符合條件的所有數據let result = try context.fetch(fetchRequest)for person in result {// 循環修改person.name = newNameperson.age = newAge}} catch {fatalError();}saveContext()} 復制代碼
  • 根據條件刪除數據
    • 與修改數據一樣,首先拿到符合刪除條件的數據
    • 循環調用context的delete()方法就可以了
    • 最后別忘記save
    // 根據姓名刪除數據func deleteWith(name: String) {let fetchRequest: NSFetchRequest = Person.fetchRequest()fetchRequest.predicate = NSPredicate(format: "name == %@", name)do {let result = try context.fetch(fetchRequest)for person in result {context.delete(person)}} catch {fatalError();}saveContext()} 復制代碼
  • 刪除所有數據
    • 獲取所有數據
    • 循環刪除
    • save
    // 刪除所有數據func deleteAllPerson() {// 這里直接調用上面獲取所有數據的方法let result = getAllPerson()// 循環刪除所有數據for person in result {context.delete(person)}saveContext()} 復制代碼

    后記

    本文運用一個簡單的示例來說明swift中如何使用CoreData,更多用法或注意事項就不一一列舉了。

    本文Demo:github.com/remember17/…
    作者GitHub:github.com/remember17

    總結

    以上是生活随笔為你收集整理的Swift实现CoreData存储数据的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。