NSUInteger numberOfChanges = moc.insertedObjects.count + moc.deletedObjects.count+moc.updatedObjects.count;
if (numberOfChanges ==0 )
{
NSAssert([moc hasChanges]==false,@"[moc hasChanges]==false");
return;
}
どういうわけか、アサーションは失敗します。なぜだろう。したがって、何も挿入されません。何も削除されません。何も更新されません。それでも [moc hasChanges] は本当ですか? これはめったに起こりません。しかし、それはまったく起こらなかったはずです。
人々が見たい場合、これは完全なコードです。
+(void)commit {
[BGHPTools breakIfLock];
NSManagedObjectContext *moc = [self managedObjectContext];
NSArray * arUpdatedObjects = moc.updatedObjects.allObjects;
NSArray * arUpdatedObjectsID = [arUpdatedObjects convertByPeformingSelector:@selector(objectID)];
NSUInteger numberOfChanges = moc.insertedObjects.count + moc.deletedObjects.count+moc.updatedObjects.count;
if (numberOfChanges ==0 )
{
//NSAssert([moc hasChanges]==false,@"[moc hasChanges]==false");
return;
}
if (arUpdatedObjectsID.count) {
while (false);
}
[BGFetchClass vAddObjectIDCachesForArray:moc.insertedObjects.allObjects];
[BGFetchClass vDeleteObjectsForArray:moc.deletedObjects.allObjects];
/*if (numberOfChanges ==0 )
{
NSAssert([moc hasChanges]==false,@"[moc hasChanges]==false");
return;
}*/
//NSAssert([moc hasChanges],@"[moc hasChanges]==true");
__block NSError *error;
__block BOOL saveSuccesfully;
[moc performBlockAndWait:^{
@synchronized([BGFetchClass class])
{
saveSuccesfully = [moc save:&error];
if (!saveSuccesfully) {
CLog(@"Error in Saving %@", error);
}
else{
}
}
}];
if (![NSThread isMainThread]) {
if (arUpdatedObjectsID.count) { //When we're adding new objects, this won't be called. That is the only time commit is called while we are synching
[BGHPTools vDoForeGroundAndWait:^{
NSManagedObjectContext * moc =[BGMDCRManagedObjectContextThreadHandler managedObjectContext];
for (NSManagedObjectID * moi in arUpdatedObjectsID) {
NSManagedObject * mo = [moc existingObjectWithID:moi error:nil];
NSAssert(mo!=nil, @"Object can't possibly be nil");
[mo turnToFault];
}
}];
}
}
NSManagedObjectContext * parentMoc = [self managedObjectContextMainContext]; //Main parent is not nsmainqueueconcurency type. Hence, this is save
[parentMoc performBlockAndWait:^{
if (![parentMoc save:&error])
{
CLog(@"Error in Saving %@", error);// handle error
}
}];
NSAssert(error==nil, @"Error must be nill");
}