import Foundation
import CoreData
class CoreDataStore: NSObject{
let storeName = "News"
let storeFilename = "News.sqlite"
var managedObjectModel: NSManagedObjectModel {
if _managedObjectModel == nil {
let modelURL = NSBundle.mainBundle().URLForResource(storeName, withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if _persistentStoreCoordinator == nil {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(storeFilename)
var error: 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
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.endIndex-1] as NSURL
}
}
import CoreData
import UIKit
class CoreDataHelper: NSObject{
let 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
var cdstore: CoreDataStore {
if _cdstore == nil {
_cdstore = CoreDataStore()
}
return _cdstore!
}
var _cdstore: CoreDataStore? = nil
var cdh: CoreDataHelper {
if _cdh == nil {
_cdh = CoreDataHelper()
}
return _cdh!
}
var _cdh: CoreDataHelper? = nil
func applicationWillTerminate(application: UIApplication!) {
self.cdh.saveContext()
}
现在就可以在程序里使用CoreData了。我会建个class将常用 *** 作写在里面。代码如下
import UIKit
import CoreData
class NewsCoreDataController:NSObject {
let store: CoreDataStore!
let 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)
}
}
这样在程序中就可以很方便简洁的 *** 作CoreData数据了。比如
let cdControl = NewsCoreDataController()
var result = cdControl.fetchOneForCheckIfExist("Sources")
第一步:创建一个 DataDemo.xcdatamodel 文件,在其中建一个实体名字为 Entity1 ,实体中建两个字段 id 和 name。第二步:为项目添加 CoreData.framework 框架,然后在 .pch 中加入 #import <coredata/coredata.h>
第三步:在 app delegate 中定义 core data 的相关对象(同时完成它们的初始化工作)
.h 文件~
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)