标签:value http expr 错误 uiview 批量 最小值 object modify
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
//MARK: - CoreData
extension ViewController{
//MARK: 获取上下文对象
func getContext() -> NSManagedObjectContext{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
//MARK: 插入班级信息
func insertClasses(){
for i in 1...100{
let classNO = Int64(i)
let name = "rg"+"\(i)"
insertClass(classno:classNO,name:name)
}
}
func insertClass(classno:Int64,name:String) {
//获取上下文对象
let context = getContext()
// //创建一个实例并赋值
// let classEntity = NSEntityDescription.insertNewObject(forEntityName: "Class", into: context) as! Class
//
// //Class对象赋值
// classEntity.classNo = classno
// classEntity.name = name
//通过指定实体名 得到对象实例
let Entity = NSEntityDescription.entity(forEntityName: "Class", in: context)
let classEntity = NSManagedObject(entity: Entity!, insertInto: context)
classEntity.setValue(classno, forKey: "classNo")
classEntity.setValue(name, forKey: "name")
do {
//保存实体对象
try context.save()
} catch {
let nserror = error as NSError
fatalError("错误:\(nserror),\(nserror.userInfo)")
}
}
//MARK: 查询班级信息
func getClass(){
// 异步fetch
//获取数据上下文对象
let context = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
// 异步请求由两部分组成:普通的request和completion handler
// 返回结果在finalResult中
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result : NSAsynchronousFetchResult!) in
//对返回的数据做处理。
let fetchObject = result.finalResult as! [Class]
for c in fetchObject{
print("\(c.classNo),\(c.name ?? "")")
}
}
// 执行异步请求调用execute
do {
try context.execute(asyncFetchRequest)
} catch {
print("error")
}
}
//MARK: 修改班级信息
func modifyClass() {
//获取委托
let app = UIApplication.shared.delegate as! AppDelegate
//获取数据上下文对象
let context = getContext()
//声明数据的请求,声明一个实体结构
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
//查询条件
fetchRequest.predicate = NSPredicate(format: "classNo = 2", "")
// 异步请求由两部分组成:普通的request和completion handler
// 返回结果在finalResult中
let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in
//对返回的数据做处理。
let fetchObject = result.finalResult! as! [Class]
for c in fetchObject{
c.name = "qazwertdfxcvg"
app.saveContext()
}
}
// 执行异步请求调用execute
do {
try context.execute(asyncFecthRequest)
} catch {
print("error")
}
}
//MARK: 删除班级信息
func deleteClass() -> Void {
//获取委托
let app = UIApplication.shared.delegate as! AppDelegate
//获取数据上下文对象
let context = getContext()
//声明数据的请求,声明一个实体结构
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
// 异步请求由两部分组成:普通的request和completion handler
// 返回结果在finalResult中
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result:NSAsynchronousFetchResult) in
//对返回的数据做处理。
let fetchObject = result.finalResult! as! [Class]
for c in fetchObject{
//所有删除信息
context.delete(c)
}
app.saveContext()
}
// 执行异步请求调用execute
do {
try context.execute(asyncFetchRequest)
} catch {
print("error")
}
}
//MARK: 统计信息
func countClass() {
//获取数据上下文对象
let context = getContext()
//声明数据的请求,声明一个实体结构
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
//请求的描述,按classNo 从小到大排序
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "classNo", ascending: true)]
//请求的结果类型
// NSManagedObjectResultType:返回一个managed object(默认值)
// NSCountResultType:返回满足fetch request的object数量
// NSDictionaryResultType:返回字典结果类型
// NSManagedObjectIDResultType:返回唯一的标示符而不是managed object
fetchRequest.resultType = .dictionaryResultType
// 创建NSExpressionDescription来请求进行平均值计算,取名为AverageNo,通过这个名字,从fetch请求返回的字典中找到平均值
let description = NSExpressionDescription()
description.name = "AverageNo"
//指定要进行平均值计算的字段名classNo并设置返回值类型
let args = [NSExpression(forKeyPath: "classNo")]
// forFunction参数有sum:求和 count:计算个数 min:最小值 max:最大值 average:平均值等等
description.expression = NSExpression(forFunction: "average:", arguments: args)
description.expressionResultType = .floatAttributeType
// 设置请求的propertiesToFetch属性为description告诉fetchRequest,我们需要对数据进行求平均值
fetchRequest.propertiesToFetch = [description]
do {
let entries = try context.fetch(fetchRequest)
let result = entries.first! as! NSDictionary
let averageNo = result["AverageNo"]!
print("\(averageNo)")
} catch {
print("failed")
}
}
//MARK:批量更新
func batchUpdate()
{
let batchUpdate = NSBatchUpdateRequest(entityName: "Class")
//所要更新的属性 和 更新的值
batchUpdate.propertiesToUpdate = ["name": 55555]
//被影响的Stores
batchUpdate.affectedStores = self.getContext().persistentStoreCoordinator!.persistentStores
//配置返回数据的类型
batchUpdate.resultType = .updatedObjectsCountResultType
//执行批量更新
do {
let batchResult = try getContext().execute(batchUpdate) as! NSBatchUpdateResult
//批量更新的结果,上面resultType类型指定为updatedObjectsCountResultType,所以result显示的为 更新的个数
print("\(batchResult.result!)")
} catch {
print("error")
}
}
}
标签:value http expr 错误 uiview 批量 最小值 object modify
原文地址:http://www.cnblogs.com/chenxiaopao/p/7816191.html