引用在AppDelegate中创建的NSPersistentSt

引用在AppDelegate中创建的NSPersistentSt

本文介绍了引用在AppDelegate中创建的NSPersistentStore实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我修改了核心数据应用程序获得的样板核心数据栈代码,将 NSPersistentStore 添加到 NSPersistentStoreCoordinator

  // MARK: - 核心数据堆栈
lazy var applicationDocumentsDirectory:NSURL = {
let urls = NSFileManager.defaultManager()。URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask)
返回urls [urls.count-1] as NSURL
}()

lazy var managedObjectModel:NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle()。URLForResource(DB,withExtension:momd)!
return NSManagedObjectModel(contentsOfURL:modelURL)!
}()

lazy var persistentStoreCoordinator:NSPersistentStoreCoordinator? = {
var coordinator:NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel:self.managedObjectModel)
var error:NSError? = nil

let firstStoreURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(first-store.sqlite)
如果coordinator !.addPersistentStoreWithType(NSSQLiteStoreType,configuration:nil,URL:firstStoreURL,options:nil ,错误:&错误)== nil {
coordinator = nil
NSLog(未解析的错误\(错误),\(错误!.userInfo))
abort
}

let secondStoreURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent(second-store.sqlite)
如果coordinator!.addPersistentStoreWithType(NSSQLiteStoreType,configuration:nil,URL:secondStoreURL,选项:nil,错误:&错误)== nil {
coordinator = nil
NSLog(未解决的错误\(错误),\(错误!.userInfo))
abort()
}
return coordinator
}()

lazy var managedObjectContext:NSManagedObjectContext? = {
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

// MARK: - 核心数据保存支持
func saveContext(){
如果let moc = self .managedObjectContext {
var error:NSError? = nil
如果moc.hasChanges&& !moc.save(& error){
NSLog(未解决的错误\(错误),\(错误!.userInfo))
abort()
} $ b b}
}

我需要在添加 NSManagedObject 下面的对象。

  let someObject = NSManagedObject(entity:someEntity,insertIntoManagedObjectContext:context )
context.assignObject(someObject,toPersistentStore:< store instance>)
  let entityDescription = NSEntityDescription.entityForName(someEntity,inManagedObjectContext:context )

let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
fetchRequest.affectedStores = [< store instance>]
我的问题是,如何获得对在AppDelegate中创建的 NSPersistentStore 的引用?



为了清楚起见,我已经知道如何获取对AppDelegate本身的引用。

  let appDelegate = UIApplication.sharedApplication()。委托为AppDelegate 

NSPersistentStore 部分是我被困的地方。






尝试创建它作为一个单独的属性在AppDelegat像这样,但我不知道如何调用它/从 persistentStoreCoordinator 添加

  var firstStore:NSPersistentStore {
var store:NSPersistentStore!
如果let coordinator = persistentStoreCoordinator {
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(first-store.sqlite)
var error:NSError?
store = coordinator.addPersistentStoreWithType(NSSQLiteStoreType,configuration:nil,URL:url,options:nil,error:& error)!
}
return store
}

属性,不会向协调器添加一个存储的新实例?

解决方案

有一个 persistentStores NSPersistentStoreCoordinator 您可以使用为此目的。它返回一个(可能) NSPersistentStore 实例的数组。

 获取第一个商店,假设它存在
let appDelegate = UIApplication.sharedApplication()。委托为AppDelegate
让firstStore = appDelegate.persistentStoreCoordinator.persistentStores [0]作为NSPersistentStore


I modified the boilerplate core data stack code you get with a core data application to add two NSPersistentStores to the NSPersistentStoreCoordinator instead of just one.

// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
    return urls[urls.count-1] as NSURL
}()

lazy var managedObjectModel: NSManagedObjectModel = {
    let modelURL = NSBundle.mainBundle().URLForResource("DB", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    var error: NSError? = nil

    let firstStoreURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("first-store.sqlite")
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: firstStoreURL, options: nil, error: &error) == nil {
        coordinator = nil        
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }

    let secondStoreURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("second-store.sqlite")
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: secondStoreURL, options: nil, error: &error) == nil {
        coordinator = nil
        NSLog("Unresolved error \(error), \(error!.userInfo)")
        abort()
    }
    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
    let coordinator = self.persistentStoreCoordinator
    if coordinator == nil {
        return nil
    }
    var managedObjectContext = NSManagedObjectContext()
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support
func saveContext() {
    if let moc = self.managedObjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save(&error) {            
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
    }
}

I need to specify the store when adding NSManagedObject objects like below.

let someObject = NSManagedObject(entity: "someEntity", insertIntoManagedObjectContext: context)
context.assignObject(someObject, toPersistentStore: <store instance>)

And specifying the stores which I need to fetch data from like this.

let entityDescription = NSEntityDescription.entityForName("someEntity", inManagedObjectContext: context)

let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
fetchRequest.affectedStores = [<store instance>]

My question is how can I get a reference to those NSPersistentStores created in the AppDelegate?

Just to be clear, I already know how to get a reference to the AppDelegate itself.

let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate

It's the getting the NSPersistentStore part is where I'm stuck.


I tried creating it as a separate property in the AppDelegat like this but I don't know how to call it/add it from persistentStoreCoordinator.

var firstStore: NSPersistentStore {
    var store: NSPersistentStore!
    if let coordinator = persistentStoreCoordinator {
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("first-store.sqlite")
        var error: NSError?
        store = coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error)!
    }
    return store
}

Besides whenever I call this property, wouldn't it add a new instance of a store to the coordinator?

解决方案

There is a persistentStores property on NSPersistentStoreCoordinator you can use for this purpose. It returns an array of (presumably) NSPersistentStore instances.

// Get the first store, assuming it exists
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let firstStore = appDelegate.persistentStoreCoordinator.persistentStores[0] as NSPersistentStore

这篇关于引用在AppDelegate中创建的NSPersistentStore实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 07:56