一、Core Data介紹
1、Core Data是iOS5之后才出現(xiàn)的一個數(shù)據(jù)持久化存儲框架,它提供了對象-關(guān)系映射(ORM)的功能,即能夠?qū)ο筠D(zhuǎn)化成數(shù)據(jù),也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成對象。
2、雖然其底層也是由類似于SQL的技術(shù)來實現(xiàn),但我們不需要編寫任何SQL語句,有點(diǎn)像Java開發(fā)中的Hibernate持久化框架
3、Core Data數(shù)據(jù)最終的存儲類型可以是:SQLite數(shù)據(jù)庫,XML,二進(jìn)制,內(nèi)存里,或自定義數(shù)據(jù)類型。
4、與SQLite區(qū)別:只能取出整個實體記錄,然后分解,之后才能得到實體的某個屬性。
二、Core Data的使用準(zhǔn)備 - 數(shù)據(jù)模型和實體類的創(chuàng)建
1、創(chuàng)建項目的時候,勾選“Use Core Data”。完畢后在 AppDelegate 中,會生成相關(guān)代碼。

2、打開項目中的 xcdatamodeld 文件,在右邊的數(shù)據(jù)模型編輯器的底部工具欄點(diǎn)擊 Add Entity 添加實體。
同時在屬性欄中對實體命名進(jìn)行修改,并在 Attribute 欄目中添加屬性。
3、點(diǎn)擊下方的 Editor Style 按鈕可以查看實體的關(guān)系圖。

4、自 iOS10 和 swift3 之后,訪問 CoreData 的方法簡潔了許多,我們不再需要手動新建對應(yīng)于 entity 的 class。
三、Core Data的使用
1、首先在代碼中引入CoreData庫
import CoreData
2、插入(保存)數(shù)據(jù)操作
/// 添加數(shù)據(jù)
func addData()
{
//獲取管理的數(shù)據(jù)上下文 對象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//創(chuàng)建User對象
let user = NSEntityDescription.insertNewObject(forEntityName: "User",
into: context) as! User
//對象賦值
user.id = 1
user.userName = "hangge"
user.password = "1234"
//保存
do {
try context.save()
print("保存成功!")
} catch {
fatalError("不能保存:\(error)")
}
}
3、查詢數(shù)據(jù)操作
/// 查詢數(shù)據(jù)
func queryData()
{
//獲取管理的數(shù)據(jù)上下文 對象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請求
let fetchRequest = NSFetchRequest<User>(entityName:"User")
fetchRequest.fetchLimit = 10 //限定查詢結(jié)果的數(shù)量
fetchRequest.fetchOffset = 0 //查詢的偏移量
//設(shè)置查詢條件
let predicate = NSPredicate(format: "id= '1' ", "")
fetchRequest.predicate = predicate
//查詢操作
do {
let fetchedObjects = try context.fetch(fetchRequest)
//遍歷查詢的結(jié)果
for info in fetchedObjects{
print("id=\(info.id)")
print("username=\(info.userName)")
print("password=\(info.password)")
}
}
catch {
fatalError("不能保存:\(error)")
}
}
4、修改數(shù)據(jù)操作
/// 修改數(shù)據(jù)操作
func modifyData()
{
//獲取管理的數(shù)據(jù)上下文 對象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請求
let fetchRequest = NSFetchRequest<User>(entityName:"User")
fetchRequest.fetchLimit = 10 //限定查詢結(jié)果的數(shù)量
fetchRequest.fetchOffset = 0 //查詢的偏移量
//設(shè)置查詢條件
let predicate = NSPredicate(format: "id= '1' ", "")
fetchRequest.predicate = predicate
//查詢操作
do {
let fetchedObjects = try context.fetch(fetchRequest)
//遍歷查詢的結(jié)果
for info in fetchedObjects{
//修改密碼
info.password = "abcd"
//重新保存
try context.save()
}
}
catch {
fatalError("不能保存:\(error)")
}
}
5、刪除數(shù)據(jù)操作
/// 刪除數(shù)據(jù)操作
func deleteData()
{
//獲取管理的數(shù)據(jù)上下文 對象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請求
let fetchRequest = NSFetchRequest<User>(entityName:"User")
fetchRequest.fetchLimit = 10 //限定查詢結(jié)果的數(shù)量
fetchRequest.fetchOffset = 0 //查詢的偏移量
//設(shè)置查詢條件
let predicate = NSPredicate(format: "id= '1' ", "")
fetchRequest.predicate = predicate
//查詢操作
do {
let fetchedObjects = try context.fetch(fetchRequest)
//遍歷查詢的結(jié)果
for info in fetchedObjects{
//刪除對象
context.delete(info)
}
//重新保存-更新到數(shù)據(jù)庫
try! context.save()
}
catch {
fatalError("不能保存:\(error)")
}
}
附:項目并未在創(chuàng)建時勾選coreData手動添加 Cord Data 支持
(1)首先在項目中創(chuàng)建一個 xcdatamodeld 文件(Data Model)。

(2)文件名建議與項目名一致
(3)接著打開 AppDelegate.swift,在里面添加 Core Data 相關(guān)的支持方法(黃色部分)
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// 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)")
}
}
}
}
(4)經(jīng)過上面的配置后,現(xiàn)在的項目就可以使用 CoreData 了
參考:
https://www.hangge.com/blog/cache/detail_767.html
https://www.hangge.com/blog/cache/detail_1841.html#
END