diff --git a/Sources/Classes/RSContext.m b/Sources/Classes/RSContext.m index 0f7558d9..bde63de2 100644 --- a/Sources/Classes/RSContext.m +++ b/Sources/Classes/RSContext.m @@ -184,31 +184,34 @@ - (void)putAdvertisementId:(NSString *_Nonnull)idfa { }); } -- (void)updateExternalIds:(NSMutableArray *)externalIds { +- (void)updateExternalIds:(NSMutableArray *)newExternalIds { dispatch_sync(queue, ^{ - if(self->_externalIds == nil) - { + if(self->_externalIds == nil){ self->_externalIds = [[NSMutableArray alloc] init]; } - NSMutableArray *newExternalIds = [externalIds mutableCopy]; - if (self->_externalIds.count > 0) { - NSMutableArray *repeatingExternalIds = [[NSMutableArray alloc] init]; - for (NSMutableDictionary *newExternalId in newExternalIds) { - for (NSMutableDictionary *externalId in self->_externalIds) { - if ([externalId[@"type"] isEqualToString:newExternalId[@"type"]]){ - externalId[@"id"] = newExternalId[@"id"]; - [repeatingExternalIds addObject:newExternalId]; - break; - } - } - } - [newExternalIds removeObjectsInArray:repeatingExternalIds]; + NSMutableDictionary *> *mergedValues = [NSMutableDictionary dictionary]; + + for (NSMutableDictionary *externalId in self.externalIds) { + NSString *type = [NSString stringWithFormat:@"%@", externalId[@"type"]]; + mergedValues[type] = [externalId mutableCopy]; } - if ([newExternalIds count]) { - [self->_externalIds addObjectsFromArray: newExternalIds]; + // Merge new externalIds into the existing merged values + for (NSMutableDictionary *newExternalId in newExternalIds) { + NSString *type = [NSString stringWithFormat:@"%@", newExternalId[@"type"]]; + NSMutableDictionary *existingMergedValue = mergedValues[type]; + + if (existingMergedValue) { + // Merge values for the same "type" + [existingMergedValue addEntriesFromDictionary:newExternalId]; + } else { + // No existing merged value for this "type," add a copy of the newExternalId + mergedValues[type] = [newExternalId mutableCopy]; + } } + + self.externalIds = [[mergedValues allValues] mutableCopy]; }); }