Coredata 是对ios 中sqlite 的封装,在xcode 中添加创建一个
<pre><code>
项目 -> new File -> Core Data -> Data Model -> 输入名字-> 创建完毕
</code></pre>
在项目中找到刚才创建的文件:
如图红色的标记:
步骤 1 : 添加一个 Entity 命名 为User
步骤 2 :向User Entity 实体类 添加属性
步骤 3: 添加属性类型
这些工作完成之后,便是将这样entity 生成代码
选择model
选择实体,点击next生成在指定目录下
最后,在项目中使用coredata ,编写两个utils 类
CoreDataHelper 类<code><pre>
// CoreDataHelper.swift
// SwiftCoreDataSimpleDemo
//
// Created by CHENHAO on 14-6-7.
// Copyright (c) 2014 CHENHAO. All rights reserved.
//
import CoreData
import UIKit
class CoreDataHelper: NSObject{
let store: CoreDataStore!
override init(){
// all CoreDataHelper share one CoreDataStore defined in AppDelegate
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.store = appDelegate.cdstore
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// Normally, you can use it to do anything.
// But for bulk data update, acording to Florian Kugler's blog about core data performance, [Concurrent Core Data Stacks – Performance Shootout](http://floriankugler.com/blog/2013/4/29/concurrent-core-data-stack-performance-shootout) and [Backstage with Nested Managed Object Contexts](http://floriankugler.com/blog/2013/5/11/backstage-with-nested-managed-object-contexts). We should better write data in background context. and read data from main queue context.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
// main thread context
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.store.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// Returns the background object context for the application.
// You can use it to process bulk data update in background.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
lazy var backgroundContext: 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.store.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var backgroundContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
backgroundContext.persistentStoreCoordinator = coordinator
return backgroundContext
}()
// save NSManagedObjectContext
func saveContext (context: NSManagedObjectContext) {
var error: NSError? = nil
if context.hasChanges && !context.save(&error) {
// Replace this implementation 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()
}
}
func saveContext () {
self.saveContext( self.backgroundContext! )
}
// call back function by saveContext, support multi-thread
func contextDidSaveContext(notification: NSNotification) {
let sender = notification.object as! NSManagedObjectContext
if sender === self.managedObjectContext {
NSLog("******** Saved main Context in this thread")
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
} else if sender === self.backgroundContext {
NSLog("******** Saved background Context in this thread")
self.managedObjectContext!.performBlock {
self.managedObjectContext!.mergeChangesFromContextDidSaveNotification(notification)
}
} else {
NSLog("******** Saved Context in other thread")
self.backgroundContext!.performBlock {
self.backgroundContext!.mergeChangesFromContextDidSaveNotification(notification)
}
self.managedObjectContext!.performBlock {
self.managedObjectContext!.mergeChangesFromContextDidSaveNotification(notification)
}
}
}
}
</code></pre>
CoreDataStore 类
<code><pre>
//
// CoreDataStore.swift
// SwiftCoreDataSimpleDemo
//
// Created by CHENHAO on 14-7-9.
// Copyright (c) 2014 CHENHAO. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStore: NSObject{
let storeName = "anjibei"
let storeFilename = "anjibei.sqlite"
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "me.iascchen.MyTTT" 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(self.storeName, 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(self.storeFilename)
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.
let dict = NSMutableDictionary()
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 as [NSObject : AnyObject])
// 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
}()
}
</code></pre>
其中
let storeName = "anjibei"
let storeFilename = "anjibei.sqlite"
为你上述创建model 文件时候的名字。
接下来呢,就是需要在appdelagete 配置声明
<pre><code>
lazy var cdstore: CoreDataStore = {
let cdstore = CoreDataStore()
return cdstore
}()
lazy var cdh: CoreDataHelper = {
let cdh = CoreDataHelper()
return cdh
}()
</code></pre>
配置完成,可以使用了。
<pre><code>
func manageDB(){
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.cdh.managedObjectContext
var row:User = NSEntityDescription.insertNewObjectForEntityForName("User",inManagedObjectContext:managedContext!) as! User
row.username = "hello coredata"
row.password = "wow"
var error: NSError?
if !managedContext!.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//fetch families
NSLog(" ======== Fetch ======== ")
var fReq: NSFetchRequest = NSFetchRequest(entityName: "User")
fReq.predicate = NSPredicate(format:"username CONTAINS 'h' ")
var sorter: NSSortDescriptor = NSSortDescriptor(key: "username" , ascending: false)
fReq.sortDescriptors = [sorter]
fReq.returnsObjectsAsFaults = false
var result = managedContext!.executeFetchRequest(fReq, error:&error)
for resultItem in result! {
var useritem = resultItem as! User
PrintUtils.printLog("username",message: "Fetched Family for \(useritem.username) ")
}
}
</code></pre>