Core Data是用來將模型對象持久化儲存的框架,可以保存XML、atomic、SQLite格式的文件。這里使用SQLite來舉例。在你新建一個工程的時候,選擇use Core Data,Xcode會幫你做一些準備工作。在這里一共有這么幾個東西,持久化儲存文件,持久化儲存協調器,托管對象模型,托管對像上下文。
- 一個托管對象模型中會有多個實體,這些實體可以儲存在不同的持久化儲存文件中
- 一個持久化儲存協調器只能和一個托管對象模型相連
- 一個或多個托管對象上下文通過訪問持久化對象儲存協調器來訪問持久化儲存文件
- 程序中操作的就是托管對象上下文
創建實體
Xcode會給你創建一個CoreDataTest.xcdatamodeld文件,這就是你管理你的對象的地方,新建實體,并在實體里建立你需要的屬性和關系等。
建立好之后就可以讓Xcode幫助你生成每個實體對應的類了:Editor -> Create NSManagedObject SubClass。對應每個實體這會生成兩個Swift文件,你的每個實體在這里都變成了 NSManagedObject的子類,這也是在代碼中我們使用的類。
托管對象
在AppDelegate里,Xcode會幫你做一些事情:
- 首先它幫你獲取了持久化儲存的目錄,這也是App一般存數據的地方:
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "edu.bupt.exialym.CoreDataTest" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
- 接著將你的模型轉換為NSManagedObject類,這里獲取的CoreDataText.momd文件非常重要,它與你的工程名相對應:
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("CoreDataTest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
持久化儲存協調器
持久化儲存器是程序訪問持久化儲存的橋梁。
在AppDelegate中,這個變量Xcode也創建好了:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
在這里,定義了與此持久化儲存協調器對應的托管對象模型、持久化儲存文件。
托管對象上下文
在AppDelegate中,Xcode還定義了托管上下文,并指向了上面的持久化儲存協調器:
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
當托管對象改變時,需要儲存當前的托管對象上下文,這時你所做的修改才能保存起來,這樣也為撤銷和重做提供了支持。增刪改查,只有查不需要保存。這個方法Xcode也在AppDelegate里生成了:
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
查
增刪改很大程度上是在查的基礎上完成的
//首先,規定獲取數據的實體
let request = NSFetchRequest(entityName: "Book")
//配置查詢條件,如果有需要還可以配置結果排序
let predicate = NSPredicate(format: "%K == %@", "name", nameText.text!)
request.predicate = predicate
var result:[NSManagedObject] = []
do{
//進行查詢,結果是一個托管對象數組
result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
} catch {}
resultText.text = ""
for item in result {
//用鍵值對的方式獲取各個值
resultText.text! += "書名:\(item.valueForKey("name") as! String) 作者:\(item.valueForKey("author") as! String)\n"
}
增
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//向指定實體中插入托管對象
let object:Book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: appDelegate.managedObjectContext) as! Book
object.name = nameText.text
object.author = authorText.text
appDelegate.saveContext()
改
let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
request.predicate = predicate
var result:[NSManagedObject] = []
do{
result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
} catch {}
if result.count != 0{
resultText.text = ""
for item in result {
//獲取到想要的對象,改想改的值
item.setValue(authorText.text, forKey: "author")
resultText.text! += "書名:\(item.valueForKey("name") as! String) 作者:\(item.valueForKey("author") as! String)\n"
}
}
}
appDelegate.saveContext()
刪
let request = NSFetchRequest(entityName: "Book")
if nameText.text != "" && authorText.text != "" {
let predicate = NSPredicate(format: "%K == %@","name", nameText.text!)
request.predicate = predicate
var result:[NSManagedObject] = []
do{
result = try appDelegate.managedObjectContext.executeFetchRequest(request) as! [NSManagedObject]
} catch {}
if result.count != 0{
for item in result {
appDelegate.managedObjectContext.deleteObject(item)
}
}
}
appDelegate.saveContext()