1,问题描述
(1)使用 Core Data 可以很方便地实现数据持久化存储。如果项目需要使用 Cord Data,只需要在创建项目的时候,勾选“Use Core Data”。

(2)这样项目创建完毕后,项目中会自动添加一个同名的 xcdatamodeld 文件。同时 AppDelegate 中也会生成相关代码。
(3)如果我们项目之前创建时忘记勾选上“Use Core Data”,现在又想用 Cord Data 框架的话,也不用重新创建工程,只要手动配置下就好了。
2,手动添加 Cord Data 支持
(1)首先在项目中创建一个 xcdatamodeld 文件(Data Model)。

(2)文件名建议与项目名一致,比如我这里叫:hangge_1841.xcdatamodeld

(3)接着打开 AppDelegate.swift,在里面添加 Core Data 相关的支持方法(黄色部分)
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "hangge_1841")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
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 {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
(4)经过上面的配置后,现在的项目就可以使用 CoreData 了。CoreData 具体用法可以参考我之前写的这篇文章:Swift – 使用Core Data进行数据持久化存储