gpt4 book ai didi

ios - iOS CoreData 上的子查询

转载 作者:行者123 更新时间:2023-11-29 11:47:47 25 4
gpt4 key购买 nike

我的 iOS 应用程序中存在 CoreData 性能问题。

我需要使用子查询子句执行查询。

让我们来解释一下。

我有一个名为 quota 的实体,它具有 groupCode 和 date 属性。 (属性比较多,暂时不导入)。

要执行我的搜索,需要两步:

  • 首先,我需要选择 groupCode 等于 quotaGroupProductParam 的所有配额项目(quotaGroupProductParam 是一个变量。对于此示例 quotaGroupProductParam = 6816)
  • 最后,对于每个结果,我需要在同一个实体中执行新的搜索,使用子句 date = result.date 和 groupCode = quotaGroupParam(quotaGroupParam 是一个变量。对于这个例子 quotaGroupParam = 58)。

例子:

NSArray *quotasGroupProduct = [[DBContext shared] executeFetchRequest:@"Quota" WithFilter:[NSPredicate predicateWithFormat:@"groupCode=%@", quotaGroupProductParam]];
for (Quota *quota in quotasGroupProduct) {
NSArray *quotasGroup = [[DBContext shared] executeFetchRequest:@"Quota" WithFilter:[NSPredicate predicateWithFormat:@"groupCode = %@ AND date = %@", quotaGroupParam, quota.date]];
if([quotasGroup count] > 0 && [quotasRepresentative count] > 0) {
[quotaDatesArray addObject:quota.date];
}
}

我想更改此代码以仅执行一个 fetchRequest。

在执行此操作的 SQL 查询下方:

select * from zquota q where zgroupCode = 58 and exists (select 1 from zquota where ZgroupCode = 6816 and zdate = q.zdate);

谁能帮帮我?

谢谢!

最佳答案

目前,quotasGroupProduct 数组中的每个 quota 都会导致额外的提取,这本身很昂贵,而且构建和解析关联的谓词也很昂贵。您可以通过更改谓词以一次执行所有这些提取来避免这种情况。请注意,要重现与当前代码相同的行为,以相反的顺序执行提取会更容易:

  1. 使用 groupCode = quotaGroupParam 获取所有配额。
  2. 将日期提取到数组中。
  3. 使用 groupCode = quotaGroupProductParam 和上述日期数组中的日期获取所有配额。
  4. 将日期提取到最终数组中。

(这样做的原因与重复有关。如果第一次提取有多个配额,并且都具有相同的日期,则中间数组将包含相同日期的重复项。但第二次提取中的 IN 子句将确保仅一个包含在最终数组中。)

NSArray *quotasGroup = [[DBContext shared] executeFetchRequest:@"Quota" WithFilter:[NSPredicate predicateWithFormat:@"groupCode=%@", quotaGroupParam]];
// extract the dates...
NSArray *datesOfInterest = [quotasGroup valueForKey:@"date"];
// execute the second fetch
NSArray *quotasGroupProduct = [[DBContext shared] executeFetchRequest:@"Quota" WithFilter:[NSPredicate predicateWithFormat:@"groupCode = %@ AND date IN %@", quotaGroupProductParam, datesOfInterest]];
// extract the dates again
NSArray *finalDatesArray = [quotasGroupProduct valueForKey:@"date"];
if ([quotasRepresentative count] > 0) {
[quotaDatesArray addObjectsFromArray:finalDatesArray];
}

因此,无论有多少项与您的谓词匹配,都只需要两次提取。我希望这会给您带来所需的性能提升。

关于ios - iOS CoreData 上的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42724314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com