Skip to content

Commit

Permalink
[Darwin] Ensure that fetch is executed on the NSManagedObjectContext …
Browse files Browse the repository at this point in the history
…private queue instead of chip dispatch queue (#14390)
  • Loading branch information
vivien-apple authored and pull[bot] committed Sep 1, 2023
1 parent bd30d6b commit 2768945
Showing 1 changed file with 27 additions and 7 deletions.
34 changes: 27 additions & 7 deletions src/platform/Darwin/KeyValueStoreManagerImpl.mm
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand Down

0 comments on commit 2768945

Please sign in to comment.