【问题标题】:NSPredicate to check property of first 5 objects in a Core Data RelationshipNSPredicate 检查核心数据关系中前 5 个对象的属性
【发布时间】:2019-03-02 18:34:14
【问题描述】:

我希望创建一个谓词来检查 Core Data 关系中前 5 个对象的 TypeID

这是我正在尝试的,但它不起作用:

int num = 5;
NSMutableArray *predicates = [[NSMutableArray alloc] init];
for (int i = 0; i < num; i++) {

    [predicates addObject:[NSPredicate predicateWithFormat:@"SELF IN %@ AND logs[%i].TypeID == 3", items, i]];

}

这给出了错误:

错误:SQLCore dispatchRequest:异常处理请求: , 不支持的函数 表达式 logs[0].TypeID 与(null)CoreData 的 userInfo: 错误:SQLCore dispatchRequest:异常处理请求: , 不支持的函数 表达式 logs[0].TypeID with userInfo of (null)

我意识到我可能做错了,那么有没有其他方法可以使用 NSPredicate 来做到这一点?

【问题讨论】:

  • 什么是日志?您的对象有属性日志?
  • 关系类型通常是无序的Set。所以 前 5 个对象 可以不同。您需要应用 one 谓词来对集合进行排序并过滤对象。
  • @E.Coms 是的。 Logs 是SELF 对象的关系。
  • @vadian 是的,它是Set。谓词如何同时排序和过滤?
  • 您可以使用NSSortDescriptor 对获取结果进行排序,然后进行过滤。或者你可以在你的核心数据模型中添加一个排序索引,并在你的谓词中使用它。

标签: ios objective-c core-data nspredicate


【解决方案1】:

如果你只想获取 5,将 fetchLimit 设置为 5。可能下面的代码不能马上运行,但原理是一样的。您可以添加属性或获取函数来分配“logs.TypeID”,例如 -(Int)myID {return logs[0].TypeID;} 然后“SELF IN %@ AND myID == 3”可以解决问题。

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity name" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@ AND logs.TypeID == 3", items];
[fetchRequest setPredicate:predicate];
fetchRequest.fetchLimit = 5;
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil) {

}

【讨论】:

    【解决方案2】:

    我不确定我是否理解这些问题,但我认为按照您的要求做是不可能的,至少不像措辞那样。似乎不可能只检查关系中的五个对象并停在那里,返回任意数量的匹配项或根本不返回任何匹配项,即使数据库中有更多匹配项。

    但是,我认为这可能就是您要了解的情况, 可以找到五个对象,它们都在 items 集合中,并且至少有一个 log 带有typeID == 3。它可以类似于 E.Coms 建议的那样完成,除了您需要一个子查询来处理关系。 (我假设日志是一对多的关系,可以是一对多或多对多)。

    请注意,以下代码未经测试:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Entity name" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@ AND SUBQUERY(logs, $log, $log.typeID == 3).@count != 0", items];
    [fetchRequest setPredicate:predicate];
    fetchRequest.fetchLimit = 5;
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      相关资源
      最近更新 更多