Swift CoreData的使用

一、Core Data介绍

1、Core Data是iOS5之后才出现的一个数据持久化存储框架,它提供了对象-关系映射(ORM)的功能,即能够将对象转化成数据,也能够将保存在数据库中的数据还原成对象。
2、虽然其底层也是由类似于SQL的技术来实现,但我们不需要编写任何SQL语句,有点像Java开发中的Hibernate持久化框架
3、Core Data数据最终的存储类型可以是:SQLite数据库,XML,二进制,内存里,或自定义数据类型。
4、与SQLite区别:只能取出整个实体记录,然后分解,之后才能得到实体的某个属性。

二、Core Data的使用准备 - 数据模型和实体类的创建

1、创建项目的时候,勾选“Use Core Data”。完毕后在 AppDelegate 中,会生成相关代码。

CoreData项目创建.png

2、打开项目中的 xcdatamodeld 文件,在右边的数据模型编辑器的底部工具栏点击 Add Entity 添加实体。
同时在属性栏中对实体命名进行修改,并在 Attribute 栏目中添加属性。

3、点击下方的 Editor Style 按钮可以查看实体的关系图。

创建coreData代码.png

4、自 iOS10 和 swift3 之后,访问 CoreData 的方法简洁了许多,我们不再需要手动新建对应于 entity 的 class。

三、Core Data的使用

1、首先在代码中引入CoreData库

import CoreData

2、插入(保存)数据操作

/// 添加数据
func addData()
{
    //获取管理的数据上下文 对象
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    //创建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、查询数据操作

/// 查询数据
func queryData()
{
    //获取管理的数据上下文 对象
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    //声明数据的请求
    let fetchRequest = NSFetchRequest<User>(entityName:"User")
    fetchRequest.fetchLimit = 10 //限定查询结果的数量
    fetchRequest.fetchOffset = 0 //查询的偏移量

    //设置查询条件
    let predicate = NSPredicate(format: "id= '1' ", "")
    fetchRequest.predicate = predicate

    //查询操作
    do {
        let fetchedObjects = try context.fetch(fetchRequest)

        //遍历查询的结果
        for info in fetchedObjects{
            print("id=\(info.id)")
            print("username=\(info.userName)")
            print("password=\(info.password)")
        }
    }
    catch {
        fatalError("不能保存:\(error)")
    }
}

4、修改数据操作

/// 修改数据操作
func modifyData()
{
    //获取管理的数据上下文 对象
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    //声明数据的请求
    let fetchRequest = NSFetchRequest<User>(entityName:"User")
    fetchRequest.fetchLimit = 10 //限定查询结果的数量
    fetchRequest.fetchOffset = 0 //查询的偏移量

    //设置查询条件
    let predicate = NSPredicate(format: "id= '1' ", "")
    fetchRequest.predicate = predicate

    //查询操作
    do {
        let fetchedObjects = try context.fetch(fetchRequest)

        //遍历查询的结果
        for info in fetchedObjects{
            //修改密码
            info.password = "abcd"
            //重新保存
            try context.save()
        }
    }
    catch {
        fatalError("不能保存:\(error)")
    }
}

5、删除数据操作

/// 删除数据操作
func deleteData()
{
    //获取管理的数据上下文 对象
    let app = UIApplication.shared.delegate as! AppDelegate
    let context = app.persistentContainer.viewContext

    //声明数据的请求
    let fetchRequest = NSFetchRequest<User>(entityName:"User")
    fetchRequest.fetchLimit = 10 //限定查询结果的数量
    fetchRequest.fetchOffset = 0 //查询的偏移量

    //设置查询条件
    let predicate = NSPredicate(format: "id= '1' ", "")
    fetchRequest.predicate = predicate

    //查询操作
    do {
        let fetchedObjects = try context.fetch(fetchRequest)

        //遍历查询的结果
        for info in fetchedObjects{
            //删除对象
            context.delete(info)
        }

        //重新保存-更新到数据库
        try! context.save()
    }
    catch {
        fatalError("不能保存:\(error)")
    }
}

附:项目并未在创建时勾选coreData手动添加 Cord Data 支持

(1)首先在项目中创建一个 xcdatamodeld 文件(Data Model)。

image.png

(2)文件名建议与项目名一致

(3)接着打开 AppDelegate.swift,在里面添加 Core Data 相关的支持方法(黄色部分)

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)经过上面的配置后,现在的项目就可以使用 CoreData 了

参考:

https://www.hangge.com/blog/cache/detail_767.html
https://www.hangge.com/blog/cache/detail_1841.html#

END

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容