今天咱們來經過建立一個小的Demo來實踐咱們的CoreDate 的學習。參考書籍Core_Data_by_Tutorialsgit
初始項目數據庫
更多關於CoreDate的基礎知識swift
二app
主要一下幾個步驟:ide
NSManagedObjectModel學習
NSPresistentStoreurl
NSPersistentStoreCoordinatorspa
NSManagedObjectContext
在這裏就很少說每個都是什麼了,能夠參考上邊給出的兩篇博客.net
Show your codecode
import CoreData class CoreDadaStack { /// model Name private let modelName = "Dog Walk" /// Document Directory URL private lazy var applicationDocumentsDirectory: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() /// Managed Object Model private lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd") return NSManagedObjectModel(contentsOfURL: modelURL!)! }() /// Presistent Store Coordinator private lazy var psc: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.modelName) do { let options = [NSMigratePersistentStoresAutomaticallyOption:true] try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) }catch { print("添加持久化存儲區錯誤") } return coordinator }() /// Managed Object Context lazy var context: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.psc return managedObjectContext }() /** Save Context Data */ func saveContext() { if context.hasChanges { do { try context.save() } catch let error as NSError { print("錯誤 ❌ \(error.localizedDescription)") abort() } } } }
選擇ViewController.swift
添加下邊代碼import CoreData
添加屬性:var managedContext: NSManagedObjectContext!
而後打開AppDelegate.swift
import CoreData
添加屬性:
lazy var coreDataStack = CoreDataStack()
在application(_:didFinishLaunchingWithOptions:)
添加下邊代碼
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let navigationController = window?.rootViewController as! UINavigationController let viewcontroller = navigationController.topViewController as! ViewController viewcontroller.managedContext = coreDataStack.context return true }
最後咱們在 UIApplicationDelegate
的兩個方法中調用存儲方法
func applicationWillTerminate(application: UIApplication) { coreDataStack.saveContext() } func applicationDidEnterBackground(application: UIApplication) { coreDataStack.saveContext() }
打開Dog Walk
添加 Dog
Entity ,添加屬性 name
類型爲 String
添加 Walk
Entity, 添加屬性 date
類型爲 Date
接下來咱們完成關係。
打開 Dog
Entity ,添加relationship
name 爲 walks
Set the destination to Walk
在屬性版中修改Type
類型,To Many
,勾選 Ordered
打開 Walk
Entity , 添加relationship
name 爲 dog
relationship 爲 Dog
Set the destination as dog and the inverse as walks.
command + n
選擇 NSManagedObject Subclass
選擇 Dog Walk model
而且選中 Dog 和 Walk entities。 語言選擇 Swift
我在生成的Walk.swift
和 Dog.swift
中都重寫了父類的方法,爲了在生成這兩個類的時候有代碼提示。
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) }
若是你上邊的步驟都已經完成了,那麼咱們就能夠開始存儲數據了。
首先在ViewController.swift
中添加一個屬性 var currentDog: Dog!
而後咱們在viewDidLoad()
中來添加一些數據
//建立一個 Entity let dogEntity = NSEntityDescription.entityForName("Dog", inManagedObjectContext: managedContext) let dogName = "Fido" //首先來檢查在數據庫中是否存在一個名爲 Fido 的狗過 let dogFetch = NSFetchRequest(entityName: "Dog") dogFetch.predicate = NSPredicate(format: "name == %@", dogName) do{ //執行查詢 let results = try managedContext.executeFetchRequest(dogFetch) as! [Dog] //若是這個狗狗存在的話直接獲取賦值給 currentDog if results.count > 0 { currentDog = results.first }else { //若是不存在 則實例化一個Dog currentDog = Dog(entity: dogEntity!, insertIntoManagedObjectContext: managedContext) currentDog.name = dogName try managedContext.save() } }catch let error as NSError{ print("Error:\(error)" + "description:\(error.localizedDescription)") }
接下來咱們來實現點擊添加按鈕以後添加新狗狗散步時間的功能。
@IBAction func add(sender: AnyObject) { //添加一個新的 Walk Entity into Core Data let walkEntity = NSEntityDescription.entityForName("Walk", inManagedObjectContext: managedContext) let walk = Walk(entity: walkEntity!, insertIntoManagedObjectContext: managedContext) walk.date = NSDate.timeIntervalSinceReferenceDate() //insert the new walk into the dog's walks set let walks = currentDog.walks!.mutableCopy() as! NSMutableOrderedSet walks.addObject(walk) currentDog.walks = walks.copy() as? NSOrderedSet //save the managed object context do { try managedContext.save() }catch let error as NSError { print("Could not save:\(error)") } tableView.reloadData() }
如今你運行程序,點擊➕就能夠看到有新的數據在列表中顯示。
咱們接下來就是要把咱們添加的數據刪除。
咱們來重寫下邊的方法
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { //選擇要刪除的walk let walkToRemove = currentDog.walks![indexPath.row] as! Walk //刪除 managedContext.deleteObject(walkToRemove) do { //保存操做 try managedContext.save() }catch let error as NSError { print("Could not save: \(error)") } // 刪除視圖中的數據 tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } }
運行你的app 來試試吧。