13.Swift CoreData

本文介绍了如何在iOS中使用Swift配合CoreData进行数据库的增删改查操作。从项目适配、引入CoreData库,到创建数据库、添加属性,再到具体的CRUD操作,详细阐述了CoreData的使用流程,并提供了相关代码示例。
摘要由CSDN通过智能技术生成

13.Swift CoreData


在Android中,一想到要操作SQLite,就觉得很繁琐;但是IOS中,有一套非常成熟的数据库API(接口)和GUI(图形用户界面),这样大大提升了用户体验,虽然,我们开发者,但是不可否认的是,我们也是一种另类的用户,一看到GUI,很多人可能更偏爱于IOS开发。

IOS数据库数据的增、删、改、查,其实也就是对NSManagedObjectContext的增、删、改、查。

项目适配CodeData

其实真的很简单,只需要你勾上User Core Data这个选项即可。

13-1

然后你会看到项目中的AppDelegate.swift文件多了不少东西。其中也包括如下:

    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.URLByAppendingPathComponent("SingleViewCoreData.sqlite")

        // 打印数据库文件存放目录
        NSLog("\(url)")

        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason

            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值