以前使用过OC版本的CoreData应该很好理解Swift方式,所以这里简单的展示一下,增删改查的方法使用,同时给大家说一下创建步骤,方便大家的使用,转载请注明出处,谢谢~

步骤一:创建一个Swift的新项目,记得勾选对应的配置项,如图:

步骤二:打开****.xcdatamodeld文件,点击Add Entity,添加一个实体类,可以自己重定义类名,然后在类中添加属性,如图:

步骤三:打开AppDelegate文件,添加相关代码,注意红色的地方要改成自己项目中对应的名称

//MARK:------注意下面的四个方法需要自己添加
    lazy var applicationDocumentsDirectory: URL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "me.appkitchen.cd" in the application's documents Application Support directory.
        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return urls[urls.count-1]
    }()
    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = Bundle.main.url(forResource: "SwiftCoreDataDemo", withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: modelURL)!
    }()
    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.appendingPathComponent("OneOneEntity.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
            
            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() 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.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        
        return coordinator
    }()
    lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

步骤四:开始写自己的增删该查方法

//增加数据
    func saveData(textStr:String) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let manageContext = appDelegate.managedObjectContext
        let entityOne = NSEntityDescription.entity(forEntityName: "OneOneEntity", in: manageContext)
        let itemS = NSManagedObject.init(entity: entityOne!, insertInto: manageContext)
        itemS.setValue(textStr, forKey: "textStr")
        do {
            try manageContext.save()
            self.dataArray.append(itemS)
            //print("..........\(itemS)")
        } catch  {
            print("存储错误...")
        }
    }
    //删除
    func deleteData(aIndexPath:IndexPath) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let manageContext = appDelegate.managedObjectContext
        
        manageContext.delete(self.dataArray[aIndexPath.row])
        
        do {
            try manageContext.save()
            self.dataArray.remove(at: aIndexPath.row)
            self.myTableView.reloadData()
        } catch  {
            print("存储错误...")
        }
    }
    //修改
    func updateData(aIndxPath:IndexPath,upStr:String) {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let manageContext = appDelegate.managedObjectContext
        //let entityOne = NSEntityDescription.entity(forEntityName: "OneOneEntity", in: manageContext)
        //创建查询请求
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>.init(entityName: "OneOneEntity")
        //获取数据
        do {
            let results = try manageContext.fetch(fetchRequest)
            //找到修改的数据
            let oneObj:NSManagedObject = results[aIndxPath.row] as! NSManagedObject
            oneObj.setValue(upStr, forKey: "textStr")
            do {
                try manageContext.save()
                do {
                    let results1 = try manageContext.fetch(fetchRequest)
                    self.dataArray = results1 as! [NSManagedObject]
                    self.myTableView.reloadData()
                } catch  {
                    print("查询错误...")
                }
            } catch  {
                print("存储错误...")
            }
            
        } catch  {
            print("修改错误...")
        }
    }
    //查询
    func lookUpData() {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let manageContext = appDelegate.managedObjectContext
        
        let fetchReq = NSFetchRequest<NSFetchRequestResult>(entityName: "OneOneEntity")
        do {
            let results = try manageContext.fetch(fetchReq)
            self.dataArray = results as! [NSManagedObject]
            self.myTableView.reloadData()
        } catch  {
            print("查询错误...")
        }
    }

效果图:(具体代码,请自行研究,如果喜欢请点Star,源码:https://github.com/hbblzjy/SwiftCoreDataDemo

     

     

Swift基础之CoreData的使用的更多相关文章

  1. swift基础:第六部分:类与对象

    http://reactnative.cn/docs/0.24/getting-started.html#content(react Native 开发文档) 互联网这个时代,你松懈一天,就会有很多很 ...

  2. swift基础:第二部分:函数和闭包

    今天本来想利用上午的时间本来打算将swift基础部分学习完的,不巧的是,后台来和我讨论用户评价的接口,讨论过后,商讨出一种可行的方案,十几分钟时间过去了,我拿到将接口介入到已经完成的页面中,完美,终于 ...

  3. Swift基础语法学习总结(转)

    Swift基础语法学习总结 1.基础  1.1) swift还是使用// 和/* */ 来注释,并且/* */允许多行注释. 1.2) swift使用print和println打印,它的传参是一个泛型 ...

  4. Swift基础语法学习总结

    Swift基础语法学习总结Swift高级语法学习总结Swift语法总结补充(一) 1.基础  1.1) swift还是使用// 和/* */ 来注释,并且/* */允许多行注释. 1.2) swift ...

  5. swift -- 基础

    swift -- 基础 1.常量和变量 常量: let 变量: var 2.声明常量和变量 常量的声明: let let  a = 1         //末尾可以不加分号,等号两边的空格必须对应(同 ...

  6. iOS Swift 模块练习/swift基础学习

    SWIFT项目练习     SWIFT项目练习2 iOS Swift基础知识代码 推荐:Swift学习使用知识代码软件 0.swift中的宏定义(使用方法代替宏) 一.视图  +控件 1.UIImag ...

  7. Swift基础学习

    Swift基础学习  http://c.biancheng.net/cpp/html/2242.html 这个网站最近看了一下,对于基本语法解释概括的相对全面,如同重新练习一遍OC似的,挺全面的,谢谢 ...

  8. swift基础语法(四) 函数、闭包(Closures)

    //函数基本定义 func 函数名(参数名:参数类型=默认值) ->返回值类型{代码块} //无参无返回值函数 func hsmin(){ } //单参无返回值函数 func prin(st:S ...

  9. Swift基础语法(二)

    操作符 swift中运算符基本基础于c,下面我就给大家白话白话那些被优化过的运算符们 //加号减号的妙用 var a= var b= -a//此时b=-1 var c = +b//此时 c=-1 va ...

随机推荐

  1. scrapy 选择器官方文档

    当抓取网页时,常见的任务是从HTML源码中提取数据.现有的一些库可以达到这个目的: BeautifulSoup lxml Scrapy 提取数据有自己的一套机制.它们被称作选择器(seletors), ...

  2. 重拾Python(3):Pandas之Series对象的使用

    Pandas是Python下最强大的数据分析和探索库,是基于Numpy库构建的,支持类似SQL的结构化数据的增.删.查.改,具有丰富的数据处理函数.Pandas有两大数据结构:Series和DataF ...

  3. 从零开始系列之vue全家桶(4)带新手小白一起搭建第一个个人网站项目

    未经允许,严禁转载,全文由blackchaos提供. 在安装好了前面大部分需要的插件,我们开始进行第一个个人项目.结合vue+vuex+vue-cli+vue-router+webpack使用. 1. ...

  4. [JSOI2007]合金

    Description 某公司加工一种由铁.铝.锡组成的合金.他们的工作很简单.首先进口一些铁铝锡合金原材料,不同种类的 原材料中铁铝锡的比重不同.然后,将每种原材料取出一定量,经过融解.混合,得到新 ...

  5. 例10-7 uva10820(欧拉)

    题意:输入n,要求满足1≤x,y≤n,且x,y互素的个数. 若输入2,则答案3为(1,1),(1,2),(2,1);所以欧拉函数求出所有数的phi值,除了1之外都加上phi值的2倍即可 通过推导: p ...

  6. Python作业之购物车

    作业之购物车 购物车的要求如下: 输入总金额 选择购买的商品,金额足够时,把选择的商品添加到购物车,金额不足时,进行提示,商品将不会添加到购物车 随时可以退出程序,同时输出已购买的商品 具体代码如下: ...

  7. Ajax来实现下拉框省市区三级联动效果(服务端基于express)

    //服务端JS代码: //提供服务端的处理 const express = require('express'); const fs = require('fs'); const app = expr ...

  8. 4月18开始看《C++Primer Plus》

    好久没有写博客了,之前也说过水平有限,也写不出什么技术博客,只能写些感悟. 过年之后,陆续做了2.3个项目,刚开始可能不太熟悉流程,怎么和页面传数据?最近一个项目1/2天就写完代码了,真的很简单,主要 ...

  9. KMP及其改进算法

    本文主要讲述KMP已经KMP的一种改进方法.若发现不正确的地方,欢迎交流指出,谢谢! KMP算法的基本思想: KMP的算法流程: 每当一趟匹配过程中出现字符比较不等时,不需回溯 i 指针,而是利用已经 ...

  10. mysql 索引列为Null的走不走索引及null在统计时的问题

    要尽可能地把字段定义为 NOT NULL,即使应用程序无须保存 NULL(没有值),也有许多表包含了可空列(Nullable Column)这仅仅是因为它为默认选项.除非真的要保存 NULL,否则就把 ...