diff --git a/MagicalRecord/Categories/NSManagedObjectContext/NSManagedObjectContext+MagicalRecord.m b/MagicalRecord/Categories/NSManagedObjectContext/NSManagedObjectContext+MagicalRecord.m index 39c3927..9fc0d24 100644 --- a/MagicalRecord/Categories/NSManagedObjectContext/NSManagedObjectContext+MagicalRecord.m +++ b/MagicalRecord/Categories/NSManagedObjectContext/NSManagedObjectContext+MagicalRecord.m @@ -64,7 +64,7 @@ static id iCloudSetupNotificationObserver = nil; } defaultManagedObjectContext_ = moc; - + [moc MR_obtainPermanentIDsBeforeSaving]; if ([MagicalRecord isICloudEnabled]) { [defaultManagedObjectContext_ MR_observeiCloudChangesInCoordinator:coordinator]; @@ -165,5 +165,24 @@ static id iCloudSetupNotificationObserver = nil; return context; } +- (void) MR_obtainPermanentIDsBeforeSaving; +{ + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(contextWillSave:) + name:NSManagedObjectContextWillSaveNotification + object:self]; +} + +- (void)contextWillSave:(NSNotification *)notification +{ + NSManagedObjectContext *context = (NSManagedObjectContext *)notification.object; + if (context.insertedObjects.count > 0) { + NSArray *insertedObjects = [[context insertedObjects] allObjects]; + MRLog(@"Context %@ is about to save. Obtaining permanent IDs for new %d inserted objects", [context MR_description], insertedObjects.count); + NSError *error; + [context obtainPermanentIDsForObjects:insertedObjects error:&error]; + [MagicalRecord handleErrors:error]; + } +} @end diff --git a/Project Files/Unit Tests/NSManagedObjectContextHelperTests.m b/Project Files/Unit Tests/NSManagedObjectContextHelperTests.m index 67a6a0a..ac09632 100644 --- a/Project Files/Unit Tests/NSManagedObjectContextHelperTests.m +++ b/Project Files/Unit Tests/NSManagedObjectContextHelperTests.m @@ -7,7 +7,7 @@ // #import "NSManagedObjectContextHelperTests.h" - +#import "SingleEntityWithNoRelationships.h"; @implementation NSManagedObjectContextHelperTests - (void) setUp @@ -35,5 +35,14 @@ assertThat([testContext parentContext], is(equalTo([NSManagedObjectContext MR_defaultContext]))); } +- (void) testThatSavedObjectsHavePermanentIDs +{ + NSManagedObjectContext *context = [NSManagedObjectContext MR_defaultContext]; + SingleEntityWithNoRelationships *entity = [SingleEntityWithNoRelationships MR_createInContext:context]; + assertThatBool([[entity objectID] isTemporaryID], equalToBool(YES)); + [context MR_save]; + assertThatBool([[entity objectID] isTemporaryID], equalToBool(NO)); +} + @end