user330739
user330739

Reputation: 455

ManagedObjectContext Saved In Memory, But Not On Disk

I am in need of assistance... been at this for too long.

What generally is the issue when I can correctly query an NSManagedObject but when I go to check the actual datastore (after multiple context saves without fails) the data doesn't exist?

My hypothesis is that the ONLY logical conclusion is that there is a threading issue. Is this correct?

Upvotes: 0

Views: 77

Answers (1)

ankhzet
ankhzet

Reputation: 2569

Depends.

If you querying objects from context, that is directly attached to persistent store, than all should be ok.

If you querying them from in-memory context, which have that directly-to-persitent-store-attached as it's parent context (which is common case for multithreaded CoreData usage), then you should push changes to parent context and then call -[save:] on that parent context.

Note. I assumed, you do perform change merges for child MO contexts. Do you? Example code:

// Core-Data MOC creation
- (NSManagedObjectContext *)managedObjectContext {
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    _managedObjectContext = ... ; // creating context, if not yet
    ...

    if (_managedObjectContext != nil) {
        [_managedObjectContext performBlockAndWait:^{
//          //NOTE: iCloud-related
//          [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(remoteChangesImport:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coordinator];
        }];
    }

    // register merge callback for child contexts!
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(localChangesSave:)
                                                 name:NSManagedObjectContextDidSaveNotification
                                               object:_managedObjectContext];

    return _managedObjectContext;
}

- (void)localChangesSave:(NSNotification *)notification {
// Changes in child context. Need to merge...

    [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}

Upvotes: 1

Related Questions