ios - 引用在 AppDelegate 中创建的 NSPersistentStore 实例

标签 ios swift core-data appdelegate nspersistentstore

我修改了通过核心数据应用程序获得的样板核心数据堆栈代码,将两个 NSPersistentStore 添加到 NSPersistentStoreCoordinator 而不是一个。

// 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()
        }
    }
}

我需要在添加 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().delegate as AppDelegate

获取 NSPersistentStore 部分是我卡住的地方。


我试过像这样在 AppDelegat 中将它创建为一个单独的属性,但我不知道如何从 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
}

此外,每当我调用此属性时,它不会向协调器添加一个新的商店实例吗?

最佳答案

有一个persistentStores propertyNSPersistentStoreCoordinator 上,您可以用于此目的。它返回一个(大概)NSPercientStore 实例的数组。

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

关于ios - 引用在 AppDelegate 中创建的 NSPersistentStore 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29074157/

相关文章:

ios - 我们如何在 Project 中找到 UIWebView 并将其替换为 WKWebView?

java - Swift 中 Java 字节数组的正确等价物是什么?

ios - 使用 RestKit 0.2 从 CoreData 获取本地数据

swift - Xcode 7 "Extra argument ' 调用中的错误“核心数据错误”

ios - 在委托(delegate)方法中使用默认行为对 UITextField 进行子类化的设计方法

ios - 谷歌地图 404 页面在路由时找不到错误

ios - 将 NSManagedObject 转换为子类返回 nil

ios - 从 SDK 返回 App

swift - 使用PHPickerViewController拍摄照片时如何获取文件名

iphone - 如何从核心数据中获取唯一字段值(song_type)