0

我在两个应用程序之间共享了相同的 .sqilte App groups

当我在 App A 中添加录音并打开 App B(首次启动)时,App B 会正确检索数据。

我想在应用程序 A 和应用程序 B(已经在后台启动)中添加录音时同步数据,应用程序 B 可以在它回到前台时检索数据。

这就是为什么当 App B 回到前台时,我将 Core Data Sack 更新为 applicationWillEnterForeground。哪种方式是正确的?

let directory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.com.sl.sharedData");

        let url = directory?.URLByAppendingPathComponent("sharedData.sqlite")
        let store = self.persistentStoreCoordinator?.persistentStoreForURL(url!)
        var error : NSError?
        if false == self.persistentStoreCoordinator?.removePersistentStore(store!, error: &error)
        {
            println("error = \(error!.localizedDescription)")
            return
        }
        let options = [
            NSMigratePersistentStoresAutomaticallyOption: true,
            NSInferMappingModelAutomaticallyOption: true,
            // Adding the journalling mode recommended by apple
            NSSQLitePragmasOption: ["journal_mode": "DELETE"]
        ]
        var failureReason = "There was an error creating or loading the application's saved data."
        if self.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason
            dict[NSUnderlyingErrorKey] = error
            error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
        _persistentStoreCoordinator = nil
        _managedObjectContext = nil
        let rootViewController = self.window!.rootViewController as ViewController
        rootViewController.context = self.managedObjectContext

不幸的是,它不能按我的意愿工作。当我进入 applicationWillEnterForeground 时,每次都会对检索到的数据进行配音。哪种方式是正确的?

// 编辑 2014/04/17 : 尝试使用 Mundi 的解决方案

我试过了NSManagedObjectContextObjectsDidChangeNotification

   func applicationWillEnterForeground(application: UIApplication) {

        NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "mergeContextChangesForNotification:",
            name: NSManagedObjectContextObjectsDidChangeNotification,
            object: managedObjectContext)

        let rootViewController = self.window!.rootViewController as ViewController
        rootViewController.context = managedObjectContext
        }
    }

func mergeContextChangesForNotification(notification : NSNotification){
        let otherContext: NSManagedObjectContext = notification.object as NSManagedObjectContext

        if((otherContext != managedObjectContext) && (otherContext.persistentStoreCoordinator == managedObjectContext.persistentStoreCoordinator)){

            managedObjectContext.performBlockAndWait{ () -> Void in

                self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
            }
        }
    }

mergeContextChangesForNotification已被调用,但我从未进入过这种情况:if otherContext != managedObjectContext) && (otherContext.persistentStoreCoordinator == managedObjectContext.persistentStoreCoordinator

4

1 回答 1

0

如果应用程序已经处于活动状态,则不应再次设置持久存储协调器。Xcode 模板中使用的标准延迟初始化已足够且可取。

相反,您可能希望收听NSManagedObjectContextObjectsDidChangeNotification并酌情更新您的 UI。

于 2015-04-16T16:53:45.023 回答