When I try to save data for private NSManagedObjectContext
I get deadlock even if operations for this context are called inside performBlock:
block. This is strange because this block should be performed asynchronosuly withouth interrupting the main UI/UX thread.
Here is the code of this method:
- (void)loadTimetableToCoreData:(id)timetable
{
// Initializing temporary context
NSManagedObjectContext *tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
tempContext.parentContext = self.moc;
[tempContext performBlock:^{
// Here is the parsing
NSLog(@"Finished loading to temp MOC");
NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:@"Timetable"];
[r setIncludesPendingChanges:NO];
NSArray *existingTimetables = [tempContext executeFetchRequest:r error:nil];
for (Timetable *table in existingTimetables) {
[tempContext deleteObject:table];
}
// Saving procedure with multithreading
NSError *error;
if (![tempContext save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
NSLog(@"Finished saving to temp MOC");
[self.moc performBlock:^{
// Save groups to presistant store
NSError *error;
if (![self.moc save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
NSLog(@"Finished saving to main MOC");
[self.writer performBlock:^{
// Save groups to presistant store
NSError *error;
if (![self.writer save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
NSLog(@"Finished saving to writer MOC");
}];
}];
}];
}
As you can see there are some NSLog
s inside this method and to visualize my problem I get stuck between Finished loading to temp MOC and Finished saving to temp MOC.
What am I doing wrong and how to unlock the main thread?
Update
Here is the screen from Instruments and what I can see... The controllerDidChangeCintent
is killing everything.
I know that this is caused by those lines from
loadTimetableToCoreData:
NSFetchRequest* r = [NSFetchRequest fetchRequestWithEntityName:@"Timetable"];
[r setIncludesPendingChanges:NO];
NSArray *existingTimetables = [tempContext executeFetchRequest:r error:nil];
for (Timetable *table in existingTimetables) {
[tempContext deleteObject:table];
}
But I can't get rid of them! Or I don't know how....