標籤:swift ios coredata objective-c
簡介
這篇文章記錄了在 IOS 中使用 Swift 操作 CoreData 的一些基礎性內容,由於缺乏文檔,基本上都是自行實驗的結果,錯漏不可避免,還請諒解。
部分內容借鑒了 Tim Roadley 的《Learning.Core.Data.for.iOS(2013.11)》, 這本書主要介紹 ObjC的 CoreData 。
建立一個新 XCode 項目
- 填寫項目相關資訊,如設定項目名稱為: SwiftCoreDataSimpleDemo, 注意選擇語言為 Swift, 並且勾選上 Use Core Data。
修改 Core Data Model
- 選擇 SwiftCoreDataSimpleDemo.xcdatamodeld 檔案,目前還是空的。
- 建立兩個 Entity, 分別命名為 Family 和 Member。
- 在產生模型檔案之前,我們可以建立一個名為 models 的 Group , 用於存放產生的模型檔案。
- 選中 SwiftCoreDataSimpleDemo.xcdatamodeld 檔案的某個 Entity 之後,能夠在 Editor 菜單中找到 Create NSManagedObject Subclass,選擇此項目,開始建立模型檔案。
- 跟隨嚮導,完成模型建立,可以選中所有的 Entity ,並將儲存位置指定為我們剛建立的 models Group 中。
- 在結束之前,XCode 會彈出對話方塊,問是否建立用於 Swift 和 ObjC 協同工作的庫檔案 SwiftCoreDataSimpleDemo-Bridging-Header.h, 此時當然是選擇 Yes。
產生完成之後,就能夠在 Project 中看見新的模型檔案了。此時,SwiftCoreDataSimpleDemo-Bridging-Header.h 還是空的,我們需要在其中增加需要被 Swift 訪問的標頭檔。結果如所示:
#import "Family.h"#import "Member.h"
修改 AppDelegate
和建立 ObjC App 類似,建立項目將操作 CoreData 的代碼添加在 AppDelegate.swift 檔案中。為了能夠使代碼更簡潔和清晰,我們將這部分代碼提煉出來,移動到 CoreDataHelper.swift 中去。
- 開啟原始的 AppDelegate.swift,在程式的後半部分,能夠看見操作 CoreData 相關的代碼.如所示。
- 建立新 CoreDataHelper.swift 檔案。修改檔案名稱為 CoreDataHelper。
- 在 AppDelegate.swift 中將
func saveContext () 及其後面的代碼選中,轉移到 CoreDataHelper.swift 檔案中。並對其做些小調整,將所用到的項目名稱提成常量,放在 CoreDataHelper 前部,這樣,以後如果需要在曆史項目中使用 CoreDataHelper,就十分方便了。
完成後的 CoreDataHelper.swift 代碼如下:
//// CoreDataHelper.swift// SwiftCoreDataSimpleDemo//// Created by CHENHAO on 14-6-7.// Copyright (c) 2014年 CHENHAO. All rights reserved.//import CoreDataclass CoreDataHelper{ let storeName = "SwiftCoreDataSimpleDemo" let storeFilename = "SwiftCoreDataSimpleDemo.sqlite" // #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn‘t already exist, it is created and bound to the persistent store coordinator for the application. var managedObjectContext: NSManagedObjectContext { if !_managedObjectContext { let coordinator = self.persistentStoreCoordinator if coordinator != nil { _managedObjectContext = NSManagedObjectContext() _managedObjectContext!.persistentStoreCoordinator = coordinator } } return _managedObjectContext! } var _managedObjectContext: NSManagedObjectContext? = nil // Returns the managed object model for the application. // If the model doesn‘t already exist, it is created from the application‘s model. var managedObjectModel: NSManagedObjectModel { if !_managedObjectModel { let modelURL = NSBundle.mainBundle().URLForResource(storeName, withExtension: "momd") _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL) } return _managedObjectModel! } var _managedObjectModel: NSManagedObjectModel? = nil // Returns the persistent store coordinator for the application. // If the coordinator doesn‘t already exist, it is created and the application‘s store added to it. var persistentStoreCoordinator: NSPersistentStoreCoordinator { if !_persistentStoreCoordinator { let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(storeFilename) var error: NSError? = nil _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application‘s resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ //println("Unresolved error \(error), \(error.userInfo)") abort() } } return _persistentStoreCoordinator! } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil // #pragma mark - Application‘s Documents directory // Returns the URL to the application‘s Documents directory. var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as NSURL } func saveContext () { var error: NSError? = nil let managedObjectContext = self.managedObjectContext if managedObjectContext != nil { if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } }}
- 修改 AppDelegate.swift。並建立一個 CoreDataHelper 的執行個體,用於操作 CoreData。
將 applicationWillTerminate(application: UIApplication) 方法之後的內容全部替換為以下代碼。
var cdh: CoreDataHelper {if !_cdh { _cdh = CoreDataHelper() } return _cdh!}var _cdh: CoreDataHelper? = nil
- 修改 AppDelegate.swift,以自動儲存 CoreData。
代碼如下:
func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. self.cdh.saveContext()}...func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application‘s managed object context before the application terminates. self.cdh.saveContext()}
操作模型對象
接下來我們將在 AppDelegate.swift 中建立一個訪問 CoreData 的 demoFamily 方法,用於操作 CoreData。這段代碼放在func applicationDidBecomeActive(application: UIApplication) 中執行,操作結果從 Log 檔案中查看。
func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. self.demoFamily()}
demoFamily() 的具體實現如下,代碼說明請參考注釋:
func demoFamily(){ var newItemNames = ["Apples", "Milk", "Bread", "Cheese", "Sausages", "Butter", "Orange Juice", "Cereal", "Coffee", "Eggs", "Tomatoes", "Fish"] // add families NSLog(" ======== Insert ======== ") for newItemName in newItemNames { var newItem: Family = NSEntityDescription.insertNewObjectForEntityForName("Family", inManagedObjectContext: self.cdh.managedObjectContext) as Family newItem.name = newItemName NSLog("Inserted New Family for \(newItemName) ") } //self.cdh.saveContext() //fetch families NSLog(" ======== Fetch ======== ") var error: NSError? = nil var fReq: NSFetchRequest = NSFetchRequest(entityName: "Family") // 設定過濾條件 fReq.predicate = NSPredicate(format:"name CONTAINS ‘B‘ ") // 設定結果定序,此處設定為按 Name 逆序 var sorter: NSSortDescriptor = NSSortDescriptor(key: "name" , ascending: false) fReq.sortDescriptors = [sorter] var result = self.cdh.managedObjectContext.executeFetchRequest(fReq, error:&error) for resultItem : AnyObject in result { var familyItem = resultItem as Family NSLog("Fetched Family for \(familyItem.name) ") } //delete families NSLog(" ======== Delete ======== ") fReq = NSFetchRequest(entityName: "Family") result = self.cdh.managedObjectContext.executeFetchRequest(fReq, error:&error) for resultItem : AnyObject in result { var familyItem = resultItem as Family NSLog("Deleted Family for \(familyItem.name) ") self.cdh.managedObjectContext.deleteObject(familyItem) } //self.cdh.saveContext() NSLog(" ======== Check Delete ======== ") result = self.cdh.managedObjectContext.executeFetchRequest(fReq, error:&error) if result.isEmpty { NSLog("Deleted All Families") } else{ for resultItem : AnyObject in result { var familyItem = resultItem as Family NSLog("Fetched Error Family for \(familyItem.name) ") } }}
Log輸出如下:
2014-06-07 14:01:53.717 SwiftCoreDataSimpleDemo[18348:1419062] Application windows are expected to have a root view controller at the end of application launch2014-06-07 14:01:54.100 SwiftCoreDataSimpleDemo[18348:1419062] ======== Insert ======== 2014-06-07 14:01:54.115 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Apples 2014-06-07 14:01:54.115 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Milk 2014-06-07 14:01:54.115 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Bread 2014-06-07 14:01:54.116 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Cheese 2014-06-07 14:01:54.116 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Sausages 2014-06-07 14:01:54.116 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Butter 2014-06-07 14:01:54.117 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Orange Juice 2014-06-07 14:01:54.117 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Cereal 2014-06-07 14:01:54.117 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Coffee 2014-06-07 14:01:54.118 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Eggs 2014-06-07 14:01:54.118 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Tomatoes 2014-06-07 14:01:54.118 SwiftCoreDataSimpleDemo[18348:1419062] Inserted New Family for Fish 2014-06-07 14:01:54.118 SwiftCoreDataSimpleDemo[18348:1419062] ======== Fetch ======== 2014-06-07 14:01:54.121 SwiftCoreDataSimpleDemo[18348:1419062] Fetched Family for Butter 2014-06-07 14:01:54.122 SwiftCoreDataSimpleDemo[18348:1419062] Fetched Family for Bread 2014-06-07 14:01:54.122 SwiftCoreDataSimpleDemo[18348:1419062] ======== Delete ======== 2014-06-07 14:01:54.123 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Tomatoes 2014-06-07 14:01:54.123 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Cereal 2014-06-07 14:01:54.123 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Orange Juice 2014-06-07 14:01:54.123 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Eggs 2014-06-07 14:01:54.124 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Milk 2014-06-07 14:01:54.124 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Butter 2014-06-07 14:01:54.124 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Sausages 2014-06-07 14:01:54.125 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Cheese 2014-06-07 14:01:54.125 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Apples 2014-06-07 14:01:54.125 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Bread 2014-06-07 14:01:54.125 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Fish 2014-06-07 14:01:54.126 SwiftCoreDataSimpleDemo[18348:1419062] Deleted Family for Coffee 2014-06-07 14:01:54.126 SwiftCoreDataSimpleDemo[18348:1419062] ======== Check Delete ======== 2014-06-07 14:01:54.127 SwiftCoreDataSimpleDemo[18348:1419062] Deleted All FamiliesProgram ended with exit code: 9
不工作的 Member.swift 代碼
參考 Swift 文檔,嘗試建立 Member.swift,編譯通過,運行測試失敗。因文檔有限,沒法進一步確定原因。記錄在此,以供大家探討。
Swift 文檔的相關說明如下,Implementing Core Data Managed Object Subclasses
Implementing Core Data Managed Object SubclassesCore Data provides the underlying storage and implementation of properties in subclasses of the NSManagedObject class. Add the @NSManaged attribute before each property definition in your managed object subclass that corresponds to an attribute or relationship in your Core Data model. Like the @dynamic attribute in Objective-C, the @NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike @dynamic, the @NSManaged attribute is available only for Core Data support.
根據文檔編寫 Member.swift 如下:
import CoreDataclass Member: NSManagedObject { @NSManaged var name: String @NSManaged var sex: String @NSManaged var birthday: NSDate}
將 SwiftCoreDataSimpleDemo-Bridging-Header.h 中的 Member.h 行注釋掉:
#import "Family.h"// #import "Member.h"
運行之後,編譯成功,但運行出錯閃退,出錯介面如下。
代碼地址
https://github.com/iascchen/SwiftCoreDataSimpleDemo/
打完收工
Author : iascchen(at)gmail(dot)com
Date : 2014-6-7
新浪微博 : @問天鼓