Coredata 是對ios 中sqlite 的封裝,在xcode 中添加創(chuàng)建一個
<pre><code>
項(xiàng)目 -> new File -> Core Data -> Data Model -> 輸入名字-> 創(chuàng)建完畢
</code></pre>
在項(xiàng)目中找到剛才創(chuàng)建的文件:
如圖紅色的標(biāo)記:
步驟 1 : 添加一個 Entity 命名 為User
步驟 2 :向User Entity 實(shí)體類 添加屬性
步驟 3: 添加屬性類型
這些工作完成之后欲侮,便是將這樣entity 生成代碼
選擇model
選擇實(shí)體佣蓉,點(diǎn)擊next生成在指定目錄下
最后涂身,在項(xiàng)目中使用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"
為你上述創(chuàng)建model 文件時(shí)候的名字老虫。
接下來呢允坚,就是需要在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>