1.建立学生实体,插入100条数据
2.按条件查询学生数据
3.统计学生信息
4.修改学生信息
5.删除学生数据
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//1.建立模型文件
//2.建立CoreDataStack
//3.设置AppDelegate
//插入数据
insertStudents()
//查询数据
fetchStudents()
//统计信息
countStudents()
//修改数据
updateStudents()
//删除数据
deleteStudents()
}
}
extension ViewController{
func insertStudents(){
let strs1 = ["a","b","c","d","e","f","g","h","i","j"]
let strs2 = ["01","02","03","04","05","06","07","08","09","10"]
for i in 0..<100 {
let sno = "\(1001+i)"
let name = strs1[i/10] + strs2[i%10]
let score = i
insertStudent(sno: sno, name: name, score: score)
}
CoreDataStack.defaultStack().saveContext()
}
func insertStudent(sno sno:String,name:String,score:Int){
let context = CoreDataStack.defaultStack().context
let student = NSEntityDescription.insertNewObjectForEntityForName("student", inManagedObjectContext: context) as! Student
student.sno = sno
student.name = name
student.score = score
}
func fetchStudents(){
let context=CoreDataStack.defaultStack().context
let request=NSFetchRequest(entityName:"Student")
let sort = NSSortDescriptor(key:"sno", ascending:true, selector:"localizedStandardCompare")
request.sortDescriptors = [sort]
//request.predicate = NSPredicate(format:"score > 60")
//request.predicate = NSPredicate(format:"name like 'a*'")
do{
let students=(try context.executeFetchRequest(request)) as! [Student]
for student in students{
print("\(student.sno!),\(student.name!),\(student.score!)")
}
}catch{
print("Fetch failed")
}
}
func countStudents(){
// 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......")
// }
let context = CoreDataStack.defaultStack().context
let request=NSFetchRequest(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
do {
let entries = (try context.executeFetchRequest(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(entityName:"Student")
request.predicate = NSPredicate(format:"name like 'a*'")
do{
let students = (try context.executeFetchRequest(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(entityName:"Student")
request.predicate = NSPredicate(format:"score < 60")
do{
let students = (try context.executeFetchRequest(request)) as! [Student]
for student in students{
context.deleteObject(student)
}
}catch{
print("Fetch failed......")
}
CoreDataStack.defaultStack().saveContext()
}
}