FetchedResultsController Swift 3 API Misuse: Attempt to serialize store access on non-owning coordinator

后端 未结 3 567
野性不改
野性不改 2021-02-13 14:11

I\'m attempting to use a fetchedResultsController to handle the results in my UITable.

It works initially when the program starts up. Then when I switch back to the inv

3条回答
  •  清酒与你
    2021-02-13 15:04

    I was running into similar issue and i moved to the new CoreData api introduced in ios10. This uses the NSPersistentContainer class to create the stack and create associated contexts. This eliminates the need to manually call save or order the creation of fetch results controller.

    Good blog post to read: https://useyourloaf.com/blog/easier-core-data-setup-with-persistent-containers/

    My setup is a follows

    create a store NSPersistentContainer

    let persistentContainer = NSPersistentContainer(name: "ModelFileName");
    

    configure settings

    let url = NSPersistentContainer.defaultDirectoryURL()
    let path = url.appendingPathComponent(persistentContainer.name);
    description.shouldAddStoreAsynchronously = true; //write to disk should happen on background thread
    self.persistentContainer.persistentStoreDescriptions = [description];
    

    load the store

    persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error {
                  fatalError("Unresolved error \(error), \(error.localizedDescription)")
            }
    
        //configure context for main view to automatically merge changes
        persistentContainer.viewContext.automaticallyMergesChangesFromParent = true;
    });
    

    in the view controller you can access the view context by calling

    persistentContainer.viewContext
    

    if you need to make changes you can call

    persistentContainer.performBackgroundTask({ (context) in ... });
    

    or you can get a background context

    let context = persistentContainer.newBackgroundContext()
    context.perform({ ... })
    

提交回复
热议问题