转载自http://www.starming.com/index.php?v=index&view=29
先创建两个类
1.
importFoundation
importCoreData
classCoreDataStore:NSObject{
letstoreName ="News"
letstoreFilename ="News.sqlite"
varmanagedObjectModel:NSManagedObjectModel{
if_managedObjectModel==nil{
letmodelURL =NSBundle.mainBundle().URLForResource(storeName, withExtension:"momd")
_managedObjectModel=NSManagedObjectModel(contentsOfURL: modelURL!)
}
return_managedObjectModel!
}
var_managedObjectModel:NSManagedObjectModel? =nil
varpersistentStoreCoordinator:NSPersistentStoreCoordinator? {
if_persistentStoreCoordinator==nil{
letstoreURL =self.applicationDocumentsDirectory.URLByAppendingPathComponent(storeFilename)
varerror:NSError? =nil
_persistentStoreCoordinator=NSPersistentStoreCoordinator(managedObjectModel:self.managedObjectModel)
if_persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration:nil, URL: storeURL, options:nil, error: &error) ==nil{
abort()
}
}
return_persistentStoreCoordinator!
}
var_persistentStoreCoordinator:NSPersistentStoreCoordinator? =nil
// #pragma mark - Documents directory
varapplicationDocumentsDirectory:NSURL{
leturls =NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
returnurls[urls.endIndex-1]as!NSURL
}
}
2.
import CoreData
import UIKit
class CoreDataHelper: NSObject{
var store: CoreDataStore!
override init(){
super.init()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.store = appDelegate.cdstore
NSNotificationCenter.defaultCenter().addObserver(self, selector: "contextDidSaveContext:", name: NSManagedObjectContextDidSaveNotification, object: nil)
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// #pragma mark - Core Data stack
// main thread context
var managedObjectContext: NSManagedObjectContext? {
if _managedObjectContext == nil {
let coordinator = self.store.persistentStoreCoordinator
if coordinator != nil {
_managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
var backgroundContext: NSManagedObjectContext? {
if _backgroundContext == nil {
let coordinator = self.store.persistentStoreCoordinator
if coordinator != nil {
_backgroundContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType)
_backgroundContext!.persistentStoreCoordinator = coordinator
}
}
return _backgroundContext!
}
var _backgroundContext: NSManagedObjectContext? = nil
// save NSManagedObjectContext
func saveContext (context: NSManagedObjectContext?) {
var error: NSError? = nil
if context != nil {
if context!.hasChanges && !context!.save(&error) {
NSLog("Unresolved error (error)")
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)
}
}
}
}
在AppDelegate里添加如下代码
// #pragma mark - Core Data Helper
varcdstore:CoreDataStore{
if_cdstore ==nil{
_cdstore = CoreDataStore()
}
return_cdstore!
}
var_cdstore:CoreDataStore? =nil
varcdh:CoreDataHelper{
if_cdh ==nil{
_cdh = CoreDataHelper()
}
return_cdh!
}
var_cdh:CoreDataHelper? =nil
funcapplicationWillTerminate(application:UIApplication) {
self.cdh.saveContext()
}
现在就可以在程序里使用CoreData了。我会建个class将常用操作写在里面。代码如下
import UIKit
import CoreData
class NewsCoreDataController:NSObject {
var store: CoreDataStore!
var cdh: CoreDataHelper!
override init() {
super.init()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
self.store = appDelegate.cdstore
self.cdh = appDelegate.cdh
}
func fetchNewestNews()->NSFetchedResultsController {
var error:NSError? = nil
var fReq:NSFetchRequest = NSFetchRequest(entityName: "News")
var sorter:NSSortDescriptor = NSSortDescriptor(key: "newsDate", ascending: false)
fReq.sortDescriptors = [sorter]
fReq.fetchBatchSize = 20
fReq.fetchLimit = 20
return NSFetchedResultsController(fetchRequest: fReq, managedObjectContext: self.cdh.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
}
//按条件检查entity是否有符合条件数据
func fetchOneWithConditionForCheckIfExist(entityName:String,condition:NSPredicate)->[AnyObject]! {
var fetchReq = NSFetchRequest(entityName: entityName)
fetchReq.predicate = condition
//fetchReq.fetchLimit = 1
var error:NSError? = nil
return self.cdh.managedObjectContext!.executeFetchRequest(fetchReq, error: &error)
}
//检查entity里是否有数据
func fetchOneForCheckIfExist(entityName:String)->[AnyObject]! {
var fetchReq = NSFetchRequest(entityName: entityName)
//fetchReq.fetchLimit = 1
var error:NSError? = nil
return self.cdh.managedObjectContext!.executeFetchRequest(fetchReq, error: &error)
}
func insertForEntityWithName(entityName:String)->AnyObject! {
return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: self.cdh.managedObjectContext!)
}
//删除一个entity里的所有数据
func deleteOneEntityAllData(entityName:String) {
var error:NSError? = nil
var fReq:NSFetchRequest = NSFetchRequest(entityName: entityName)
var result = self.cdh.backgroundContext!.executeFetchRequest(fReq, error: &error)
println(result!.count)
for resultItem in result! {
self.cdh.backgroundContext!.deleteObject(resultItem as! NSManagedObject)
}
self.save()
}
func save() {
self.cdh.saveContext(self.cdh.managedObjectContext)
}
}