appdelegate里生成
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded 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.
*/
let container = NSPersistentContainer(name: "coreDataTest")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
建模不多說 注意實(shí)例化對(duì)象出錯(cuò)的話clean強(qiáng)制退出,重新編譯下
方法
//寫入數(shù)據(jù)
func insertClass(name: String, score: Double) {
let context = appDelegate.persistentContainer.viewContext
let people = People(context: context)
people.name = name
people.score = score
print("正在保存")
//保存對(duì)象實(shí)體
appDelegate.saveContext()
}
//讀取所有數(shù)據(jù)(影響性能销斟,不建議用)
func fetchAllData() {
var peoples : [People] = []
do {
peoples = try appDelegate.persistentContainer.viewContext.fetch(People.fetchRequest())
} catch {
print(error)
}
}
//排序讀取所有數(shù)據(jù) (全局變量 var fc: NSFetchedResultsController<People>!)
func fetchData2() {
//請(qǐng)求結(jié)果類型是People
let request: NSFetchRequest<People> = People.fetchRequest()
//按照name升序
let sd = NSSortDescriptor(key: "name", ascending: true)
//NSSortDescriptor指定請(qǐng)求結(jié)果如何排序
request.sortDescriptors = [sd]
let context = appDelegate.persistentContainer.viewContext
fc = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
fc.delegate = self
do {
try fc.performFetch()
if let objects = fc.fetchedObjects {
peoples = objects
}
} catch {
print(error)
}
}
//遵守NSFetchedResultsControllerDelegate代理督暂,與tableview綁定
extension ViewController : NSFetchedResultsControllerDelegate {
//當(dāng)控制器開始處理內(nèi)容變化時(shí)
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableview.beginUpdates()
}
//內(nèi)容發(fā)生變更時(shí)
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .delete:
tableview.deleteRows(at: [indexPath!], with: .automatic)
case .insert:
tableview.insertRows(at: [newIndexPath!], with: .automatic)
case .update:
tableview.reloadRows(at: [indexPath!], with: .automatic)
default:
tableview.reloadData()
}
if let objects = controller.fetchedObjects {
peoples = objects as! [People]
}
}
//當(dāng)控制器已經(jīng)處理完變更時(shí)
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableview.endUpdates()
}
}
//刪除數(shù)據(jù)
//按條刪除
let context = appDelegate.persistentContainer.viewContext
context.delete(self.fc.object(at: IndexPath))
appDelegate.saveContext()
//刪除2
//刪除數(shù)據(jù)
func delData() {
let context = appDelegate.persistentContainer.viewContext
let request: NSFetchRequest<People> = People.fetchRequest()
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: request) { (result:NSAsynchronousFetchResult) in
//對(duì)返回的數(shù)據(jù)做處理纠修。
let fetchObject = result.finalResult!
for c in fetchObject{
//所有刪除信息
context.delete(c)
}
self.appDelegate.saveContext()
}
do {
try context.execute(asyncFetchRequest)
} catch {
print(error)
}
}
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
//MARK: - CoreData
extension ViewController{
//MARK: 獲取上下文對(duì)象
func getContext() -> NSManagedObjectContext{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
//MARK: 插入班級(jí)信息
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) {
//獲取上下文對(duì)象
let context = getContext()
// //創(chuàng)建一個(gè)實(shí)例并賦值
// let classEntity = NSEntityDescription.insertNewObject(forEntityName: "Class", into: context) as! Class
//
// //Class對(duì)象賦值
// classEntity.classNo = classno
// classEntity.name = name
//通過指定實(shí)體名 得到對(duì)象實(shí)例
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 {
//保存實(shí)體對(duì)象
try context.save()
} catch {
let nserror = error as NSError
fatalError("錯(cuò)誤:\(nserror),\(nserror.userInfo)")
}
}
//MARK: 查詢班級(jí)信息
func getClass(){
// 異步fetch
//獲取數(shù)據(jù)上下文對(duì)象
let context = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
// 異步請(qǐng)求由兩部分組成:普通的request和completion handler
// 返回結(jié)果在finalResult中
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result : NSAsynchronousFetchResult!) in
//對(duì)返回的數(shù)據(jù)做處理。
let fetchObject = result.finalResult as! [Class]
for c in fetchObject{
print("\(c.classNo),\(c.name ?? "")")
}
}
// 執(zhí)行異步請(qǐng)求調(diào)用execute
do {
try context.execute(asyncFetchRequest)
} catch {
print("error")
}
}
//MARK: 修改班級(jí)信息
func modifyClass() {
//獲取委托
let app = UIApplication.shared.delegate as! AppDelegate
//獲取數(shù)據(jù)上下文對(duì)象
let context = getContext()
//聲明數(shù)據(jù)的請(qǐng)求,聲明一個(gè)實(shí)體結(jié)構(gòu)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
//查詢條件
fetchRequest.predicate = NSPredicate(format: "classNo = 2", "")
// 異步請(qǐng)求由兩部分組成:普通的request和completion handler
// 返回結(jié)果在finalResult中
let asyncFecthRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result: NSAsynchronousFetchResult!) in
//對(duì)返回的數(shù)據(jù)做處理啸如。
let fetchObject = result.finalResult! as! [Class]
for c in fetchObject{
c.name = "qazwertdfxcvg"
app.saveContext()
}
}
// 執(zhí)行異步請(qǐng)求調(diào)用execute
do {
try context.execute(asyncFecthRequest)
} catch {
print("error")
}
}
//MARK: 刪除班級(jí)信息
func deleteClass() -> Void {
//獲取委托
let app = UIApplication.shared.delegate as! AppDelegate
//獲取數(shù)據(jù)上下文對(duì)象
let context = getContext()
//聲明數(shù)據(jù)的請(qǐng)求腥寇,聲明一個(gè)實(shí)體結(jié)構(gòu)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
// 異步請(qǐng)求由兩部分組成:普通的request和completion handler
// 返回結(jié)果在finalResult中
let asyncFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { (result:NSAsynchronousFetchResult) in
//對(duì)返回的數(shù)據(jù)做處理成翩。
let fetchObject = result.finalResult! as! [Class]
for c in fetchObject{
//所有刪除信息
context.delete(c)
}
app.saveContext()
}
// 執(zhí)行異步請(qǐng)求調(diào)用execute
do {
try context.execute(asyncFetchRequest)
} catch {
print("error")
}
}
//MARK: 統(tǒng)計(jì)信息
func countClass() {
//獲取數(shù)據(jù)上下文對(duì)象
let context = getContext()
//聲明數(shù)據(jù)的請(qǐng)求,聲明一個(gè)實(shí)體結(jié)構(gòu)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Class")
//請(qǐng)求的描述赦役,按classNo 從小到大排序
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "classNo", ascending: true)]
//請(qǐng)求的結(jié)果類型
// NSManagedObjectResultType:返回一個(gè)managed object(默認(rèn)值)
// NSCountResultType:返回滿足fetch request的object數(shù)量
// NSDictionaryResultType:返回字典結(jié)果類型
// NSManagedObjectIDResultType:返回唯一的標(biāo)示符而不是managed object
fetchRequest.resultType = .dictionaryResultType
// 創(chuàng)建NSExpressionDescription來請(qǐng)求進(jìn)行平均值計(jì)算麻敌,取名為AverageNo,通過這個(gè)名字掂摔,從fetch請(qǐng)求返回的字典中找到平均值
let description = NSExpressionDescription()
description.name = "AverageNo"
//指定要進(jìn)行平均值計(jì)算的字段名classNo并設(shè)置返回值類型
let args = [NSExpression(forKeyPath: "classNo")]
// forFunction參數(shù)有sum:求和 count:計(jì)算個(gè)數(shù) min:最小值 max:最大值 average:平均值等等
description.expression = NSExpression(forFunction: "average:", arguments: args)
description.expressionResultType = .floatAttributeType
// 設(shè)置請(qǐng)求的propertiesToFetch屬性為description告訴fetchRequest术羔,我們需要對(duì)數(shù)據(jù)進(jìn)行求平均值
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
//配置返回?cái)?shù)據(jù)的類型
batchUpdate.resultType = .updatedObjectsCountResultType
//執(zhí)行批量更新
do {
let batchResult = try getContext().execute(batchUpdate) as! NSBatchUpdateResult
//批量更新的結(jié)果,上面resultType類型指定為updatedObjectsCountResultType乙漓,所以result顯示的為 更新的個(gè)數(shù)
print("\(batchResult.result!)")
} catch {
print("error")
}
}
}