CoreData初次实践(一)

前端之家收集整理的这篇文章主要介绍了CoreData初次实践(一)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天我们来通过创建一个小的Demo来实践我们的CoreDate 的学习。参考书籍Core_Data_by_Tutorials

初始项目

更多关于CoreDate的基础知识

创建Core Data Stack

主要一下几个步骤:

  1. NSManagedObjectModel

  2. NSPresistentStore

  3. NSPersistentStoreCoordinator

  4. NSManagedObjectContext
    在这里就不多说每一个都是什么了,可以参考上边给出的两篇博客

Show your code

  1. import CoreData
  2.  
  3. class CoreDadaStack {
  4. /// model Name
  5. private let modelName = "Dog Walk"
  6. /// Document Directory URL
  7. private lazy var applicationDocumentsDirectory: NSURL = {
  8. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory,inDomains: .UserDomainMask)
  9. return urls[urls.count - 1]
  10. }()
  11. /// Managed Object Model
  12. private lazy var managedObjectModel: NSManagedObjectModel = {
  13. let modelURL = NSBundle.mainBundle().URLForResource(self.modelName,withExtension: "momd")
  14. return NSManagedObjectModel(contentsOfURL: modelURL!)!
  15. }()
  16. /// Presistent Store Coordinator
  17. private lazy var psc: NSPersistentStoreCoordinator = {
  18. let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
  19. let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(self.modelName)
  20. do {
  21. let options = [NSMigratePersistentStoresAutomaticallyOption:true]
  22. try coordinator.addPersistentStoreWithType(NSsqliteStoreType,configuration: nil,URL: url,options: options)
  23. }catch {
  24. print("添加持久化存储区错误")
  25. }
  26. return coordinator
  27. }()
  28. /// Managed Object Context
  29. lazy var context: NSManagedObjectContext = {
  30. var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
  31. managedObjectContext.persistentStoreCoordinator = self.psc
  32. return managedObjectContext
  33. }()
  34. /**
  35. Save Context Data
  36. */
  37. func saveContext() {
  38. if context.hasChanges {
  39. do {
  40. try context.save()
  41. } catch let error as NSError {
  42. print("错误 ❌ \(error.localizedDescription)")
  43. abort()
  44. }
  45. }
  46. }
  47. }

选择ViewController.swift添加下边代码
import CoreData

添加属性
var managedContext: NSManagedObjectContext!

然后打开AppDelegate.swift

import CoreData
添加属性

lazy var coreDataStack = CoreDataStack()

application(_:didFinishLaunchingWithOptions:)添加下边代码

  1. func application(application: UIApplication,didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
  2. let navigationController = window?.rootViewController as! UINavigationController
  3. let viewcontroller = navigationController.topViewController as! ViewController
  4. viewcontroller.managedContext = coreDataStack.context
  5. return true
  6. }

最后我们在 UIApplicationDelegate的两个方法调用存储方法

  1. func applicationWillTerminate(application: UIApplication) {
  2. coreDataStack.saveContext()
  3. }
  4. func applicationDidEnterBackground(application: UIApplication) {
  5. coreDataStack.saveContext()
  6. }

Modeling your data

打开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.

Adding managed object subclasses

command + n 选择 NSManagedObject Subclass 选择 Dog Walk model 并且选中 Dog 和 Walk entities。 语言选择 Swift

我在生成Walk.swiftDog.swift中都重写了父类方法,为了在生成这两个类的时候有代码提示

  1. override init(entity: NSEntityDescription,insertIntoManagedObjectContext context: NSManagedObjectContext?) {
  2. super.init(entity: entity,insertIntoManagedObjectContext: context)
  3. }

A walk down persistence lane

如果你上边的步骤都已经完成了,那么我们就可以开始存储数据了。

首先在ViewController.swift添加一个属性 var currentDog: Dog! 然后我们在viewDidLoad()中来添加一些数据

  1. //创建一个 Entity
  2. let dogEntity = NSEntityDescription.entityForName("Dog",inManagedObjectContext: managedContext)
  3. let dogName = "Fido"
  4. //首先来检查在数据库中是否存在一个名为 Fido 的狗过
  5. let dogFetch = NSFetchRequest(entityName: "Dog")
  6. dogFetch.predicate = NSPredicate(format: "name == %@",dogName)
  7. do{
  8. //执行查询
  9. let results = try managedContext.executeFetchRequest(dogFetch) as! [Dog]
  10. //如果这个狗狗存在的话直接获取赋值给 currentDog
  11. if results.count > 0 {
  12. currentDog = results.first
  13. }else {
  14. //如果不存在 则实例化一个Dog
  15. currentDog = Dog(entity: dogEntity!,insertIntoManagedObjectContext: managedContext)
  16. currentDog.name = dogName
  17. try managedContext.save()
  18. }
  19. }catch let error as NSError{
  20. print("Error:\(error)" + "description:\(error.localizedDescription)")
  21. }

接下来我们来实现点击添加按钮之后添加新狗狗散步时间的功能

  1. @IBAction func add(sender: AnyObject) {
  2. //添加一个新的 Walk Entity into Core Data
  3. let walkEntity = NSEntityDescription.entityForName("Walk",inManagedObjectContext: managedContext)
  4. let walk = Walk(entity: walkEntity!,insertIntoManagedObjectContext: managedContext)
  5. walk.date = NSDate.timeIntervalSinceReferenceDate()
  6. //insert the new walk into the dog's walks set
  7. let walks = currentDog.walks!.mutableCopy() as! NSMutableOrderedSet
  8. walks.addObject(walk)
  9. currentDog.walks = walks.copy() as? NSOrderedSet
  10. //save the managed object context
  11. do {
  12. try managedContext.save()
  13. }catch let error as NSError {
  14. print("Could not save:\(error)")
  15. }
  16. tableView.reloadData()
  17. }

现在你运行程序,点击➕就可以看到有新的数据在列表中显示

Deleting objects from Core Data

我们接下来就是要把我们添加的数据删除
我们来重写下边的方法

  1. func tableView(tableView: UITableView,commitEditingStyle editingStyle: UITableViewCellEditingStyle,forRowAtIndexPath indexPath: NSIndexPath) {
  2. if editingStyle == .Delete {
  3. //选择要删除的walk
  4. let walkToRemove = currentDog.walks![indexPath.row] as! Walk
  5. //删除
  6. managedContext.deleteObject(walkToRemove)
  7. do {
  8. //保存操作
  9. try managedContext.save()
  10. }catch let error as NSError {
  11. print("Could not save: \(error)")
  12. }
  13. // 删除视图中的数据
  14. tableView.deleteRowsAtIndexPaths([indexPath],withRowAnimation: .Automatic)
  15. }
  16. }

运行你的app 来试试吧。

完成的项目

猜你在找的Swift相关文章