一、Core Data介紹
1晓猛、Core Data是iOS5之后才出現(xiàn)的一個(gè)數(shù)據(jù)持久化存儲(chǔ)框架饿幅,它提供了對(duì)象-關(guān)系映射(ORM)的功能,即能夠?qū)?duì)象轉(zhuǎn)化成數(shù)據(jù)戒职,也能夠?qū)⒈4嬖跀?shù)據(jù)庫中的數(shù)據(jù)還原成對(duì)象栗恩。
2、雖然其底層也是由類似于SQL的技術(shù)來實(shí)現(xiàn)洪燥,但我們不需要編寫任何SQL語句磕秤,有點(diǎn)像Java開發(fā)中的Hibernate持久化框架
3、Core Data數(shù)據(jù)最終的存儲(chǔ)類型可以是:SQLite數(shù)據(jù)庫捧韵,XML市咆,二進(jìn)制,內(nèi)存里再来,或自定義數(shù)據(jù)類型蒙兰。
4、與SQLite區(qū)別:只能取出整個(gè)實(shí)體記錄芒篷,然后分解搜变,之后才能得到實(shí)體的某個(gè)屬性。
二针炉、Core Data的使用準(zhǔn)備 - 數(shù)據(jù)模型和實(shí)體類的創(chuàng)建
1挠他、創(chuàng)建項(xiàng)目的時(shí)候,勾選“Use Core Data”篡帕。完畢后在 AppDelegate 中殖侵,會(huì)生成相關(guān)代碼。
2镰烧、打開項(xiàng)目中的 xcdatamodeld 文件愉耙,在右邊的數(shù)據(jù)模型編輯器的底部工具欄點(diǎn)擊 Add Entity 添加實(shí)體。
同時(shí)在屬性欄中對(duì)實(shí)體命名進(jìn)行修改拌滋,并在 Attribute 欄目中添加屬性朴沿。
3、點(diǎn)擊下方的 Editor Style 按鈕可以查看實(shí)體的關(guān)系圖败砂。
4赌渣、自 iOS10 和 swift3 之后,訪問 CoreData 的方法簡(jiǎn)潔了許多昌犹,我們不再需要手動(dòng)新建對(duì)應(yīng)于 entity 的 class坚芜。
三、Core Data的使用
1斜姥、首先在代碼中引入CoreData庫
import CoreData
2鸿竖、插入(保存)數(shù)據(jù)操作
/// 添加數(shù)據(jù)
func addData()
{
//獲取管理的數(shù)據(jù)上下文 對(duì)象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//創(chuàng)建User對(duì)象
let user = NSEntityDescription.insertNewObject(forEntityName: "User",
into: context) as! User
//對(duì)象賦值
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ù)上下文 對(duì)象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請(qǐng)求
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ù)上下文 對(duì)象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請(qǐng)求
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ù)上下文 對(duì)象
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//聲明數(shù)據(jù)的請(qǐng)求
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{
//刪除對(duì)象
context.delete(info)
}
//重新保存-更新到數(shù)據(jù)庫
try! context.save()
}
catch {
fatalError("不能保存:\(error)")
}
}
附:項(xiàng)目并未在創(chuàng)建時(shí)勾選coreData手動(dòng)添加 Cord Data 支持
(1)首先在項(xiàng)目中創(chuàng)建一個(gè) xcdatamodeld 文件(Data Model)。
(2)文件名建議與項(xiàng)目名一致
(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)在的項(xiàng)目就可以使用 CoreData 了
參考:
https://www.hangge.com/blog/cache/detail_767.html
https://www.hangge.com/blog/cache/detail_1841.html#
END