今天我们来通过创建一个小的Demo来实践我们的CoreDate 的学习。参考书籍Core_Data_by_Tutorials
更多关于CoreDate的基础知识
创建Core Data Stack
主要一下几个步骤:
NSManagedObjectModel
NSPresistentStore
NSPersistentStoreCoordinator
NSManagedObjectContext
在这里就不多说每一个都是什么了,可以参考上边给出的两篇博客
Show your code
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()
}
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.swift
和 Dog.swift
中都重写了父类的方法,为了在生成这两个类的时候有代码提示。
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
A walk down persistence lane
如果你上边的步骤都已经完成了,那么我们就可以开始存储数据了。
首先在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()
}
现在你运行程序,点击➕就可以看到有新的数据在列表中显示。
Deleting objects from Core Data
我们接下来就是要把我们添加的数据删除。
我们来重写下边的方法
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 来试试吧。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。