coreData數據操做

// 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() }
總結:
增:
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
//
// // 構建抓取請求
// 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...")
// }
相關文章
相關標籤/搜索