bandejapaisa
bandejapaisa

Reputation: 26952

ManagedObject has nil context after save

This is on a background thread. It's a private concurrency type context and it's performed within context performBlock. I'm doing it right, at least I think I am.

I'm not a beginner to core data, however I could be missing something obvious - as I've been staring at this a while.

Here is the code:

FFXCollection *backgroundCollection = (FFXCollection *) [context objectWithID:collectionID];

//At this point backgroundCollection.managedObjectContext is the same as context

NSError *error = nil;
[context save:&error];
NSLog(@"error %@", error); //Note that there is no error here

if (!backgroundCollection.managedObjectContext) {
DLog(@"why not?"); //At this point the managedObjectContext is nil!!!
}

Why is the managedObjectContext becoming nil inside the managed object?

The example is contrived, but demonstrates my problem. In my actually code, a save occurs and then i'm trying to set up a relationship. Then when another save occurs I get a validation error because of the above.

Thanks

Upvotes: 0

Views: 261

Answers (1)

Mark McCorkle
Mark McCorkle

Reputation: 9414

Use existingObjectWithID instead.

existingObjectWithID:error: Returns the object for the specified ID.

  • (NSManagedObject *)existingObjectWithID:(NSManagedObjectID )objectID error:(NSError *)error Parameters objectID The object ID for the requested object. error If there is a problem in retrieving the object specified by objectID, upon return contains an error that describes the problem. Return Value The object specified by objectID. If the object cannot be fetched, or does not exist, or cannot be faulted, it returns nil.

Discussion If there is a managed object with the given ID already registered in the context, that object is returned directly; otherwise the corresponding object is faulted into the context.

This method might perform I/O if the data is uncached.

Unlike objectWithID:, this method never returns a fault.

Availability Available in OS X v10.6 and later. See Also – objectWithID: – objectRegisteredForID: Declared In NSManagedObjectContext.h

Upvotes: 1

Related Questions