From c88bc6bf2eef9ddd5fe4cac012a82a3926a90be7 Mon Sep 17 00:00:00 2001 From: Jon Brooks Date: Thu, 24 Jul 2014 23:09:39 -0700 Subject: [PATCH] =?UTF-8?q?Fix=20Core=20Data=20threading=20problem=20with?= =?UTF-8?q?=20AFMMRecordResponseSerializer.=20=20The=20serializer=20does?= =?UTF-8?q?=20its=20work=20on=20a=20background=20thread,=20therefore=20the?= =?UTF-8?q?=20RecordResponse=20needs=20to=20be=20instantiated=20with=20a?= =?UTF-8?q?=20background=20context,=20and=20transfer=20to=20the=20main=20t?= =?UTF-8?q?hread=E2=80=99s=20context=20is=20done=20via=20-performBlockAndW?= =?UTF-8?q?ait:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AFMMRecordResponseSerializer.m | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Source/AFMMRecordResponseSerializer/AFMMRecordResponseSerializer.m b/Source/AFMMRecordResponseSerializer/AFMMRecordResponseSerializer.m index eabcf91..78029d3 100644 --- a/Source/AFMMRecordResponseSerializer/AFMMRecordResponseSerializer.m +++ b/Source/AFMMRecordResponseSerializer/AFMMRecordResponseSerializer.m @@ -108,10 +108,15 @@ - (NSManagedObjectContext *)backgroundContext { - (NSArray *)recordsFromMMRecordResponse:(MMRecordResponse *)recordResponse backgroundContext:(NSManagedObjectContext *)backgroundContext { - __block NSMutableArray *objectIDs = [NSMutableArray array]; + NSMutableArray *objectIDs = [NSMutableArray array]; [backgroundContext performBlockAndWait:^{ + NSError *error; NSArray *records = [recordResponse records]; + if (![backgroundContext save:&error]) { + NSLog(@"%s encountered error saving: %@", __PRETTY_FUNCTION__, error); + return; + } for (MMRecord *record in records) { [objectIDs addObject:[record objectID]]; @@ -120,9 +125,12 @@ - (NSArray *)recordsFromMMRecordResponse:(MMRecordResponse *)recordResponse NSMutableArray *records = [NSMutableArray array]; - for (NSManagedObjectID *objectID in objectIDs) { - [records addObject:[self.context objectWithID:objectID]]; - } + + [self.context performBlockAndWait:^{ + for (NSManagedObjectID *objectID in objectIDs) { + [records addObject:[self.context objectWithID:objectID]]; + } + }]; return records; } @@ -179,7 +187,7 @@ - (id)responseObjectForResponse:(NSURLResponse *)response MMRecordResponse *recordResponse = [MMRecordResponse responseFromResponseObjectArray:responseArray initialEntity:initialEntity - context:self.context + context:backgroundContext options:options]; NSArray *records = [self recordsFromMMRecordResponse:recordResponse