之前ios开发使用的是object-c的coredata来对sqllite数据库增删改查操作,使用教程如下:http://www.tpyyes.com/a/kuozhan/2017/0403/88.html,现在准备用下swift3 coredata来对sqlite进行增删改查操作,使用也差不多,下面将一一讲解。
1)下面开始学习ios coredata的使用,本开发工具为xcode8.3.3。首先在新建项目的时候勾选“use Core Data”,如图,如果项目已经建好。可以选择项目右键-new File-IOS-Data Model。
项目新建成功之后,会在项目中自动生成一个coredata的模型文件,如下图所示。
2)点击如上的coredata模型文件之后就可以创建数据库表了,如图所示,
第1步:选择model模型文件。
第2步:添加sqllite数据库表对应的实体类,如Student类。
第3步:已经创建的coredata实体类。
第4步:添加实体类对应的属性,以后会自动生成对应的数据库表字段。
3)自动生成coredata实体类,如图所示,由于mac不方便截图,在此采用别人的图片解释。
通过此步骤之后设计的数据表就会自动生成student对应的swift实体类了,如下图。
4)下面是coredata对sqllite数据库的student表增删改查以及分页查询等步骤了,代码如下。
import UIKit import CoreData class SinforData: NSObject { var _context:NSManagedObjectContext? override init(){ //上下文 let context = NSManagedObjectContext.init(concurrencyType:NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) // 2. 上下文关连数据库 // 2.1 model模型文件,nil为默认名称 let model = NSManagedObjectModel.mergedModel(from: nil) // 2.2 持久化存储调度器 // 持久化,把数据保存到一个文件,而不是内存 let store = NSPersistentStoreCoordinator.init(managedObjectModel: model!) // 2.3 设置CoreData数据库的名字和路径 let doc = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String let sqlitePath = doc+"/ContactsData.sqlite" print("sqlitePath====\(sqlitePath)") //异常捕获 do { //创建数据库 try store.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: NSURL.fileURL(withPath:sqlitePath), options: nil) } catch let error as NSError{ print("创建数据库失败: \(error.localizedDescription)") } context.persistentStoreCoordinator = store _context = context } //增加数据 func insertStudent() { let stu = NSEntityDescription.insertNewObject(forEntityName: "Student", into: _context!) as! Student stu.id = 1 stu.username = "zhangsan" stu.password = "66666666" stu.phone = "100000000" do { try _context?.save() print("数据保存成功") } catch let error as NSError{ print("数据保存失败: \(error.localizedDescription)") } } //删除数据 func deleteStudent(id : Int) -> () { let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Student") let pre = NSPredicate.init(format: "id=%d",id) request.predicate = pre do { let result = try _context?.fetch(request) let resultData = result as! [Student] for stu in resultData { _context?.delete(stu) } try _context?.save() print("数据删除成功") } catch let error as NSError { print("数据删除失败: \(error.localizedDescription)") } } //修改数据,例如只修改电话 func updateStudent(phone:String, id:Int) -> () { let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Student") let pre = NSPredicate.init(format: "id=%d", id) request.predicate = pre do { let result = try _context?.fetch(request) let resultData = result as! [Student] for stu in resultData { stu.phone = phone } try _context?.save() print("数据修改成功") } catch let error as NSError { print("数据修改失败: \(error.localizedDescription)") } } //查询数据,根据id查询 func findStudentById(id : Int) -> NSArray { let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Student") let pre = NSPredicate.init(format: "id=%d", id) request.predicate = pre let mutArr = NSMutableArray.init() do { let result = try _context?.fetch(request) let resultData = result as! [Student] for stu in resultData { let dict = NSMutableDictionary.init() dict.setValue(stu.id, forKey: "id") dict.setValue(stu.username, forKey: "username") dict.setValue(stu.password, forKey: "password") dict.setValue(stu.phone, forKey: "phone") mutArr.add(dict) } } catch{ print("数据查询失败") } return mutArr } //根据id倒序排序查询,批量查询 func findAllStudent() -> NSArray { let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Student") let sort = NSSortDescriptor.init(key: "id", ascending: false) request.sortDescriptors = [sort] let mutArr = NSMutableArray.init() do { let result = try _context?.fetch(request) let resultData = result as! [Student] for stu in resultData { let dict = NSMutableDictionary.init() dict.setValue(stu.id, forKey: "id") dict.setValue(stu.username, forKey: "username") dict.setValue(stu.password, forKey: "password") dict.setValue(stu.phone, forKey: "phone") mutArr.add(dict) } } catch{ print("数据查询失败") } return mutArr } //分页查询,参数为当前页 func findStudentByPage(page : Int) -> NSArray { let request = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Student") //每页显示条数 request.fetchLimit = 2 //从第几条数据开始查,计算公式:(当前页-1) * 每页显示条数 request.fetchOffset = (page - 1) * 2 let mutArr = NSMutableArray.init() do { let result = try _context?.fetch(request) let resultData = result as! [Student] for stu in resultData { let dict = NSMutableDictionary.init() dict.setValue(stu.id, forKey: "id") dict.setValue(stu.username, forKey: "username") dict.setValue(stu.password, forKey: "password") dict.setValue(stu.phone, forKey: "phone") mutArr.add(dict) } } catch{ print("数据查询失败") } return mutArr } }
5)在ViewController.swift里面写代码测试一下我们定义的增删改查方法。
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //SinforData.init().insertStudent() //SinforData.init().updateStudent(phone: "11111111111", id: 2) //SinforData.init().deleteStudent(id: 3) //let dict = SinforData.init().findStudentById(id: 4)[0] as! NSMutableDictionary //print("学生的名字:\(String(describing: dict.object(forKey: "username")))") //let stuArr = SinforData.init().findAllStudent() let stuArr = SinforData.init().findStudentByPage(page: 1) for arr in stuArr { let dict = arr as! NSMutableDictionary let id = dict.object(forKey: "id") let username = dict.object(forKey: "username") print("学生的名字:\(String(describing: id))=====\(String(describing: username))") } } }
注意事项:当我们在第3步骤新建完coredata实体类之后会报student类重复定义的错误,如:Invalid redeclaration of 'Student',则我们要删除掉student相关的实体类文件,因为有model模型文件就不需要导入这两个文件了,点击项目进入。
全部完成!