From 27689454b71fda4fd88028f9327b89b649d93d6e Mon Sep 17 00:00:00 2001 From: Vivien Nicolas Date: Thu, 27 Jan 2022 19:04:00 +0100 Subject: [PATCH] [Darwin] Ensure that fetch is executed on the NSManagedObjectContext private queue instead of chip dispatch queue (#14390) --- .../Darwin/KeyValueStoreManagerImpl.mm | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/src/platform/Darwin/KeyValueStoreManagerImpl.mm b/src/platform/Darwin/KeyValueStoreManagerImpl.mm index a8068d2fcf6ed6..95f6b46d5b1094 100644 --- a/src/platform/Darwin/KeyValueStoreManagerImpl.mm +++ b/src/platform/Darwin/KeyValueStoreManagerImpl.mm @@ -117,7 +117,16 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context } request.predicate = [NSPredicate predicateWithFormat:@"key = %@", key]; - NSArray * result = [gContext executeFetchRequest:request error:error]; + __block NSError * fetchError = nil; + __block NSArray * result; + [gContext performBlockAndWait:^{ + result = [gContext executeFetchRequest:request error:&fetchError]; + }]; + + if (error != nil) { + *error = fetchError; + } + if (result == nil) { return nullptr; } @@ -226,10 +235,14 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context return CHIP_NO_ERROR; } - [gContext deleteObject:item]; + __block BOOL success = NO; + __block NSError * error = nil; + [gContext performBlockAndWait:^{ + [gContext deleteObject:item]; + success = [gContext save:&error]; + }]; - NSError * error = nil; - if (![gContext save:&error]) { + if (!success) { ChipLogError(DeviceLayer, "Error saving context: %s", error.localizedDescription.UTF8String); return CHIP_ERROR_INTERNAL; } @@ -246,13 +259,20 @@ - (instancetype)initWithContext:(nonnull NSManagedObjectContext *)context KeyValueItem * item = FindItemForKey([[NSString alloc] initWithUTF8String:key], nil); if (!item) { item = [[KeyValueItem alloc] initWithContext:gContext key:[[NSString alloc] initWithUTF8String:key] value:data]; - [gContext insertObject:item]; + [gContext performBlockAndWait:^{ + [gContext insertObject:item]; + }]; } else { item.value = data; } - NSError * error = nil; - if (![gContext save:&error]) { + __block BOOL success = NO; + __block NSError * error = nil; + [gContext performBlockAndWait:^{ + success = [gContext save:&error]; + }]; + + if (!success) { ChipLogError(DeviceLayer, "Error saving context: %s", error.localizedDescription.UTF8String); return CHIP_ERROR_INTERNAL; }