Automatically obtain permanent IDs when saving the default context. This should fix several crashes the community is hitting

Added tests
This commit is contained in:
Stephen Vanterpool
2012-09-27 22:55:56 -07:00
parent 346631ba9e
commit 0e34179760
2 changed files with 30 additions and 2 deletions

View File

@@ -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

View File

@@ -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