swift中使用CoreData實現增刪查改

來源:互聯網
上載者:User

標籤:coredata   swift   entity   持久化   

1.建立CoreData項目

建立項目時勾選 User Core Data

2.建立實體(Entity)

建立項目後,可以看到目錄中有一個.xcdatamodeld檔案。開啟它,點擊下方Add Entity按鈕即可建立新的實體。這裡,我建立了Student屍體,兩個屬性分別是建立時間data和名字name。完成後點擊右側Show the Data Model Inspector按鈕,裡面有Name和Class兩個選項,分別是實體名稱和要產生的類名。
完成後,選擇菜單Editor–>Create NSManagedObject Subclass…即可完成建立StudentManagedObject實體。


代碼如下:

import Foundationimport CoreData@objc(StudentManagedObject)class StudentManagedObject: NSManagedObject {    @NSManaged var date: NSDate    @NSManaged var name: String}
3.建立模型

既然有了實體,為什麼還要建立模型呢?這是基於分層設計考慮的,上面一步生產的實體是NSManagedObject的子類,從層級考慮是屬於持久層。持久層和業務層,展示層分離,在項目邏輯比較複雜的時候會體現出很大的優勢。因此,我這裡再建立一個繼承NSObject的StudentModel模型,屬性和StudentManagedObject完全一致。

代碼如下:

import UIKitclass StudentModel: NSObject {    var name: String?    var date: NSDate?}
4.建立BaseDao基類

CoreData項目建立的時候,在AppDelegate中會自動產生四個參數:
applicationDocumentsDirectory 這個參數是資料庫檔案的路徑
managedObjectModel 資料庫所有實體或資料結構,包含各實體的定義資訊
persistentStoreCoordinator 相當於資料庫的串連
managedObjectContext 被管理物件內容,可以在上下文中實現尋找,刪除,插入等操作,最後需要同步
雖然看上去很複雜,用到的主要還是最後一個managedObjectContext。

預設這幾個參數是在AppDelegeta中,為了構建一個統一的資料庫提供者,我們需要建立一個BaseDao類,所有然後把四個參數拷貝過去,所有資料庫訪問Dao都繼承這個基類,這樣就可以方便調用。代碼如下:

////  BaseDao.swift//  CoreDataDemo////  Copyright (c) 2015年 worthy.zhang. All rights reserved.//import UIKitimport CoreDataclass BaseDao: NSObject {    // MARK: - Core Data stack    lazy var applicationDocumentsDirectory: NSURL = {        // The directory the application uses to store the Core Data store file. This code uses a directory named "com.worthy.CoreDataDemo" in the application‘s documents Application Support directory.        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)        return urls[urls.count-1] as! NSURL        }()    lazy var managedObjectModel: NSManagedObjectModel = {        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.        let modelURL = NSBundle.mainBundle().URLForResource("CoreDataDemo", withExtension: "momd")!        return NSManagedObjectModel(contentsOfURL: modelURL)!        }()    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {        // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added 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.        // Create the coordinator and store        var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataDemo.sqlite")        var error: NSError? = nil        var failureReason = "There was an error creating or loading the application‘s saved data."        if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {            coordinator = nil            // Report any error we got.            var dict = [String: AnyObject]()            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application‘s saved data"            dict[NSLocalizedFailureReasonErrorKey] = failureReason            dict[NSUnderlyingErrorKey] = error            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)            // Replace this with code to handle the error appropriately.            // abort() 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.            NSLog("Unresolved error \(error), \(error!.userInfo)")            abort()        }        return coordinator        }()    lazy var managedObjectContext: NSManagedObjectContext? = {        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.        let coordinator = self.persistentStoreCoordinator        if coordinator == nil {            return nil        }        var managedObjectContext = NSManagedObjectContext()        managedObjectContext.persistentStoreCoordinator = coordinator        return managedObjectContext        }()}
5.建立Data Access ObjectsStudentDao

在StudentDao實現對Student的增刪查改等操作,具體方法代碼如下,需要注意模型StudentModel與實體StudentManagedObject之間的轉換。
查詢:

func findAll()-> NSMutableArray {        println(self.applicationDocumentsDirectory.description)        let cxt = self.managedObjectContext        let entityDescription = NSEntityDescription.entityForName("Student", inManagedObjectContext:cxt!        )        let request = NSFetchRequest()        request.entity = entityDescription        var error: NSError? = nil        var listData:[AnyObject]? = cxt?.executeFetchRequest(request, error: &error)        var resListData: NSMutableArray = NSMutableArray()        for data in listData as! [StudentManagedObject] {            var entity = data            var model = StudentModel()            model.name = entity.name            model.date = entity.date            resListData.addObject(model)        }        return resListData    }

新增:

func insert(student: StudentModel){        let cxt = self.managedObjectContext        let entity = NSEntityDescription.insertNewObjectForEntityForName("Student", inManagedObjectContext: cxt!) as! StudentManagedObject        entity.name = student.name!        entity.date = NSDate()        var error: NSError? = nil        if (self.managedObjectContext?.save(&error) != nil) {            println("插入成功")        }else{            println("插入失敗")        }    }

刪除:

func remove(student:StudentModel){        let ctx = self.managedObjectContext        let entityDescription = NSEntityDescription.entityForName("Student", inManagedObjectContext: ctx!)        let request = NSFetchRequest()        request.entity = entityDescription        request.predicate = NSPredicate(format: "date == %@", student.date!)        var error: NSError? = nil        let listData:[AnyObject]? = ctx?.executeFetchRequest(request, error: &error)        for data in listData as! [StudentManagedObject] {            ctx?.deleteObject(data)            var savingError: NSError? = nil            if ctx?.save(&savingError) != nil {                println("刪除成功")            }else{                println("刪除失敗")            }        }    }

修改:

func modify(student:StudentModel){        let ctx = self.managedObjectContext        let entityDescription = NSEntityDescription.entityForName("Student", inManagedObjectContext: ctx!)        let request = NSFetchRequest()        request.entity = entityDescription        request.predicate = NSPredicate(format: "date == %@", student.date!)        var error: NSError? = nil        let listData:[AnyObject]? = ctx?.executeFetchRequest(request, error: &error)        for data in listData as! [StudentManagedObject] {            data.name = student.name!            var savingError: NSError? = nil            if ctx?.save(&savingError) != nil {                println("修改成功")            }else{                println("修改失敗")            }        }    }

最後,通過調用sharedDao返回唯一執行個體。

private let sharedInstance = StudentDao()class StudentDao: BaseDao {    class var sharedDao : StudentDao {        return sharedInstance    }......}
6.Demo示範

Demo中通過調用StudentDao中的四個方法,示範了簡單的增刪查改操作。

Demo地址:https://github.com/WorthyZhang/CoreDataDemo

swift中使用CoreData實現增刪查改

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.