CoreData是蘋果自帶的一種持久化數(shù)據(jù)存儲(chǔ)的方式,網(wǎng)上很多人說使用起來麻煩,其實(shí)正真使用后發(fā)現(xiàn)還是蠻方便的厢绝,又是系統(tǒng)自帶的买决,其實(shí)我還是蠻推薦使用的
一沛婴、基本使用
-
創(chuàng)建
-
創(chuàng)建項(xiàng)目的時(shí)候勾選CoreData
項(xiàng)目創(chuàng)建.png -
創(chuàng)建項(xiàng)目的時(shí)候如果未選擇CoreData的話也沒有關(guān)系,可以在項(xiàng)目中選擇new->file(comand+n)督赤。找到CoreData->Data Model嘁灯,創(chuàng)建
項(xiàng)目中創(chuàng)建.png
-
-
Appdelegate中的一些配置
- 如果你是創(chuàng)建項(xiàng)目的時(shí)候就選擇了CoreData的話,你會(huì)發(fā)現(xiàn)在Appdelegate中會(huì)有這么一段代碼躲舌,但是這個(gè)是在iOS10的環(huán)境下的丑婿,如果你的項(xiàng)目需要支持9,8没卸,7的話羹奉,就不能這么使用了,Xcode會(huì)報(bào)錯(cuò)的约计。诀拭。。
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.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "CoreDataDemo")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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 parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
- 如果你是后來在項(xiàng)目中新建的Data Model的話煤蚌,上面這一段代碼需要自行添加耕挨,下面的一段,在iOS7尉桩,8俗孝,9,10下都可以的魄健,建議大家替換掉
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.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.hongyu.wsl.BellEdu" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
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.
//Resource的名字最好是和Data Model的名字相同
let modelURL = Bundle.main.url(forResource: "CoreDataDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
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.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
/// 數(shù)據(jù)遷移,option使用于一般的數(shù)據(jù)遷移
let option = [NSMigratePersistentStoresAutomaticallyOption:NSNumber(value: true),NSInferMappingModelAutomaticallyOption:NSNumber(value: true)]
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: option)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
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
}()
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
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
- 為了方便使用我們定一個(gè)全局的CONTEXT
let CONTEXT = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
-
數(shù)據(jù)模型的創(chuàng)建
-
找到Data Model赋铝,點(diǎn)擊Add Entity,
Add Entity.png -
輸入model的類名沽瘦,它的屬性定義革骨,屬性的類型等
Entity.png -
Editor->Creat NSManagedObject Subclass 創(chuàng)建數(shù)據(jù)模型
數(shù)據(jù)模型創(chuàng)建.png - 創(chuàng)建成功后农尖,會(huì)生成DemoModel+CoreDataClass.swift和DemoModel+CoreDataProperties.swift這2個(gè)文件
下一節(jié):CoreData的使用(二)---增刪改查