引用在AppDelegate中创建的NSPersistentStore实例

时间:2015-03-16 10:09:22

标签: ios swift core-data appdelegate nspersistentstore

我修改了使用核心数据应用程序获得的样板核心数据堆栈代码,将NSPersistentStore添加到NSPersistentStoreCoordinator而不只是一个。{/ p>

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

除了我打电话给这个属性,它不会向协调员添加一个新的商店实例吗?

2 个答案:

答案 0 :(得分:1)

您可以在persistentStores上使用NSPersistentStoreCoordinator property来实现此目的。它返回一个(可能是)NSPersistentStore个实例的数组。

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

答案 1 :(得分:0)

要在app delegate中获取属性的引用,您需要首先获取app delegate引用:

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

然后您可以获取并使用appDelegate对象中的任何属性

let someObject = NSManagedObject(entity: "someEntity",insertIntoManagedObjectContext: context)
context.assignObject(someObject, toPersistentStore: appDelegate.persistentStoreCoordinator)