【问题标题】:retrieving data from coredata where entity has NSSet从实体具有 NSSet 的 coredata 中检索数据
【发布时间】:2013-06-10 00:47:14
【问题描述】:

我正在尝试使用谓词来获取我要搜索的数据位于 NSSet 中的数据

@property (nonatomic, retain) NSSet *categories;
@property (nonatomic, retain) NSString *otherDetails;
@property (nonatomic, retain) NSNumber *id;

NSSet 类别由另一个实体组成,包含:

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSNumber *id;

然后尝试通过谓词获取它

NSFetchRequest *fetcher =[NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
fetcher.predicate = [NSPredicate predicateWithFormat:@categories in  %@", catList];

catList 在哪里:

NSmutableArray *catList = [[NSMutableArray alloc] init];

并填充了数据

这给了我以下错误

'NSInvalidArgumetException', reason: 'unimplemented SQL generation for predicate: (categories IN {"this", "that"});

我尝试将其更改为使用 NSSet 之类的字段

fetcher.predicate = [NSPredicate predicateWithFormat:@categories.name in  %@", catList];

但这不起作用。

如果我将谓词更改为使用NSString,它不会出错,但由于数据不同,不会返回任何结果。

fetcher.predicate = [NSPredicate predicateWithFormat:@categories in  %@", catList];

那么我必须怎么做才能使用谓词对NSSet进行查询?

更新: 从那以后我发现这个How to check if an objects is inside of a NSSet of objects by using predicateWithFormat in CoreData? 可能会解决发布的问题,但我已经简化了一点。

我实际上拥有的是另一个实体,其中包含我正在搜索的大量详细信息,然后与我的“MyEntity”实体具有多对一的关系。

我的搜索实体:

@property (nonatomic, retain) NSNumber *searchField1;
@property (nonatomic, retain) NSNumber *searchField2;
@property (nonatomic, retain) MyEntity *myEntity;
@property (nonatomic, retain) NSNumber *id;

还有这样的 fetchrequest

NSFetchRequest *fetcher =[NSFetchRequest fetchRequestWithEntityName:@"MySearchEntity"];
fetcher.predicate = [NSPredicate predicateWithFormat:@"myEntity.otherDetails CONTAINS %@ && searchField1 <= %f && searchField2 >= %f && myEntity.categories.name in  %@", catList];

所以该语句的其余部分有效,但我仍然无法通过 MyEntities 与类别的多对多关系对其进行过滤。

【问题讨论】:

  • 你的谓词的目标是什么?
  • 就是将类别限制为选择添加到catList中的那些。
  • 由于对于每个对象,类别都是一组(许多)对象,您究竟想获取什么?所有类别等于 catList 或 catList 子集的对象?还是所有具有至少一类 catList 的对象?
  • catList 是所有可能类别的子集(通过其他地方的用户交互设置)。
  • 这不能回答我的问题。您要获取哪些对象?

标签: ios sqlite core-data nsset


【解决方案1】:

要查找相关MyEntity 对象在给定集中至少具有一个类别的MySearchEntity 对象,您可以使用谓词

NSArray *catList = array of Category objects;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY myEntity.categories IN %@", catList];

或者,如果类别按名称给出:

NSArray *catList = array of NSString objects;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY myEntity.categories.name IN %@", catList];

【讨论】:

  • 太棒了。 “ANY”是我所缺少的,它让世界变得与众不同。感谢马丁在这方面的帮助。我已将此标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多