// 1. 建立模型文件
// 2. 建立CoreDataStack
// 3. 设置AppDelegate
接着
//
// CoreDataStack.swift
// CoreDataStackDemo
//
// Created by wangbiao on 15/10/29.
// Copyright © 2015年 wangbiao. All rights reserved.
//
import CoreData
class CoreDataStack: NSObject {
// MARK: - Properties
let context: NSManagedObjectContext
let coordinator: NSPersistentStoreCoordinator
let model: NSManagedObjectModel
let store: NSPersistentStore?
// MARK: - Singleton
static func defaultStack() -> CoreDataStack {
return instance
}
fileprivate static let instance = CoreDataStack()
fileprivate override init() {
// 构建托管对象模型
let bundle = Bundle.main
let modelURL = bundle.url(forResource: "Test", withExtension: "momd")!
model = NSManagedObjectModel(contentsOf: modelURL)!
// 构建持久化存储助理
coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
// 构建托管对象上下文,并且将助理连接到上下文
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = coordinator
// 构建持久化存储
let manager = FileManager.default
let urls = manager.urls(for: .documentDirectory, in: .userDomainMask)
let documentsURL = urls.first!
let storeURL = documentsURL.appendingPathComponent("Test")
store = (try! coordinator.addPersistentStore(ofType: NSSQLiteStoreType,
configurationName: nil, at: storeURL, options: nil))
}
// MARK: - Function
func saveContext () {
if context.hasChanges {
do {
try context.save()
} catch {
print("Save failed...")
}
}
}
}
接着实现数据操作
//新增数据
func insertStudent(sno: String, name: String, score: Int) {
// 获取上下文(也就是从”coreData基础“里面的那个类里面获取)
let context = CoreDataStack.defaultStack().context
// 构建实体对象
let student = NSEntityDescription.insertNewObject(forEntityName: "Student",
into: context) as! Student
// 设置相关属性
student.sno = sno
student.name = name
student.score = score as NSNumber?
}
// 查询数据
func fetchStudents() {
// 获取上下文
let context = CoreDataStack.defaultStack().context
// 构建抓取请求
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
// 指定按照学号(sno)升序排列
let sort = NSSortDescriptor(key: "sno", ascending: true,
selector: #selector(NSString.localizedStandardCompare(_:)))
request.sortDescriptors = [sort]
// 构建查询条件
// request.predicate = NSPredicate(format: "score > 60")
// request.predicate = NSPredicate(format: "name like 'a*'")
do {
let students = (try context.fetch(request)) as! [Student]
for student in students {
print("(student.sno!), (student.name!), (student.score!)")
}
} catch {
print("Fetch failed...")
}
}
// 统计信息
func countStudents() {
// // 1. 统计分数大于90的人数
//
// // 获取上下文
// let context = CoreDataStack.defaultStack().context
//
// // 构建抓取请求
// let request = NSFetchRequest(entityName: "Student")
// request.predicate = NSPredicate(format: "score > 90")
// request.resultType = .CountResultType
//
// do {
// let entries = (try context.executeFetchRequest(request))
// let count = entries.first!.integerValue
// print("Count: (count)")
// } catch {
// print("Fetch failed...")
// }
// 2. 计算平均分数
// 获取上下文
let context = CoreDataStack.defaultStack().context
// 构建抓取请求
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
request.resultType = .dictionaryResultType // 指定返回结果为字典
// 构建表达式
let description = NSExpressionDescription()
description.name = "AverageScore"
let args = [NSExpression(forKeyPath: "score")]
description.expression = NSExpression(forFunction: "average:", arguments: args)
description.expressionResultType = .floatAttributeType // 指定返回值类型
// 将求平均值的表达式设置给request的属性
request.propertiesToFetch = [description]
do {
let entries = (try context.fetch(request))
let result = entries.first! as! NSDictionary
let averageScore = result["AverageScore"]!
print("Average: (averageScore)")
} catch {
print("Fetch failed...")
}
}
// 修改数据
func updateStudents() {
// 获取上下文
let context = CoreDataStack.defaultStack().context
// 构建抓取请求
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
request.predicate = NSPredicate(format: "name like 'a*'")
do {
let students = (try context.fetch(request)) as! [Student]
for student in students {
student.score = 100
}
} catch {
print("Fetch failed...")
}
// 保存
CoreDataStack.defaultStack().saveContext()
// 备注: 批量更新 & 异步操作 ???
}
// 删除数据
func deleteStudents() {
// 获取上下文
let context = CoreDataStack.defaultStack().context
// 构建抓取请求
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
request.predicate = NSPredicate(format: "score < 60")
do {
let students = (try context.fetch(request)) as! [Student]
for student in students {
context.delete(student)
}
} catch {
print("Fetch failed...")
}
// 保存
CoreDataStack.defaultStack().saveContext()
}
总结:
增:
1:获取上下文
如:let context = CoreDataStack.defaultStack().context
2:构建实体对象
如:let student = NSEntityDescription.insertNewObject(forEntityName: "Student",
into: context) as! Student
3:设置相关属性
如: student.sno = sno
4:保存数据
如:CoreDataStack.defaultStack().saveContext()
修改,删除
1:获取上下文
2:构建抓取请求
如:let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
3:给抓去请求设置相关属性吧
如:
//相当于给它设置约束
request.predicate = NSPredicate(format: "name like 'a*'")
// 指定返回结果为字典(修改,删除一般不用设置这个)
request.resultType = .dictionaryResultType
4:执行抓取操作
do {
let students = (try context.fetch(request)) as! [Student]
for student in students {
//修改如:student.score = 100
//删除如:context.delete(student)
}
} catch {
print("Fetch failed...")
}
5:保存数据
查询
1:获取上下文
2:构建抓取请求
3:指定按照学号(sno)升序排列(其实此部可以省略)
let sort = NSSortDescriptor(key: "sno", ascending: true,
selector: #selector(NSString.localizedStandardCompare(_:)))
request.sortDescriptors = [sort]
4:执行抓取语句
do {
let students = (try context.fetch(request)) as! [Student]
for student in students {
print("(student.sno!), (student.name!), (student.score!)")
}
} catch {
print("Fetch failed...")
}
5:释放资源
统计
1:获取上下文
2:构建抓取请求
3:指定按照学号(sno)升序排列(其实此部可以省略)
let sort = NSSortDescriptor(key: "sno", ascending: true,
selector: #selector(NSString.localizedStandardCompare(_:)))
request.sortDescriptors = [sort]
4: 构建表达式(average是聚合函数,当然还有其他的)
如:let description = NSExpressionDescription()
description.name = "AverageScore"
let args = [NSExpression(forKeyPath: "score")]
description.expression = NSExpression(forFunction: "average:", arguments: args)
description.expressionResultType = .floatAttributeType // 指定返回值类型
5:将求平均值的表达式设置给request的属性
如request.propertiesToFetch = [description]
4:执行抓取语句
do {
let entries = (try context.fetch(request))
let result = entries.first! as! NSDictionary
let averageScore = result["AverageScore"]!
print("Average: (averageScore)")
} catch {
print("Fetch failed...")
}
5:释放资源
当然,这个只是一个例子而已,不是所有的统计例子都要那么复杂的
如下面这个例子
// 1. 统计分数大于90的人数
//
// // 获取上下文
// let context = CoreDataStack.defaultStack().context
//
// // 构建抓取请求![](https://common.cnblogs.com/images/loading.gif)
![](https://common.cnblogs.com/images/loading.gif)
// let request = NSFetchRequest(entityName: "Student")
// request.predicate = NSPredicate(format: "score > 90")
// request.resultType = .CountResultType
//
// do {
// let entries = (try context.executeFetchRequest(request))
// let count = entries.first!.integerValue
// print("Count: (count)")
// } catch {
// print("Fetch failed...")
// }