// 1. 創建模型文件
// 2. 創建CoreDataStack
// 3. 設置AppDelegateexpress
接着swift
//
// 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...") } } } }
接着實現數據操做app
//新增數據
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() }