NSPredicate等价于SQL的GROUP BY [英] NSPredicate something equivalent of SQL's GROUP BY

查看:450
本文介绍了NSPredicate等价于SQL的GROUP BY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简化:
在名为cards的表中有3列。

To simplify: There are 3 columns in a table named cards.

id packTitle term

id packTitle term

id是一个列 - 整数0 ..... 100

id is a column - integers from 0.....100

packTitle - 描述包的字符串,假设有3种包PACK1,PACK2, PACK3

packTitle - string describing packs, lets say there are 3 kinds of pack PACK1, PACK2, PACK3

term - 101个项目的不同未排序名称。

term - different unsorted names of 101 items.

由SQL语句

select packTitle from cards group by packTitle;

我可以得到3个项目的列表。

I can get list of 3 items.

您可以建议NSPredicate等效的SQL语句GROUP BY。我需要一个数组来填充UITableView。

Could you suggest NSPredicate equivalent of SQL statement GROUP BY. I need to get an array to populate in UITableView.

推荐答案

CoreData是一个对象图管理框架,而不是SQL数据存储。因此,你应该尽快 - 让自己脱离SQL的心态。 NSPredicate 旨在作为对象图中限定对象的一个​​非惊喜谓词。因此,您可以获取与查询匹配的所有对象,但这不同于将这些结果分组。如果您要执行汇总操作,请使用键值编码的收集操作符。下面,核心数据可以将这些转换为合理的SQL,但这只是一个实现细节。

CoreData is an object graph management framework, not a SQL data store. Thus, you should—as quickly as possible—get yourself out of the SQL mindset. NSPredicate is intended as a—no surprise—predicate for qualifying objects in the object graph. Thus you can fetch all the objects that match a query, but that is not the same as grouping those results. If you want to do aggregate operations, use Key-Value coding's collection operators. Under the hood, Core Data may convert these to sensible SQL, but that's exclusively an implementation detail.

在这种情况下,集合 packTitle 的价值与

In this case, you can get the set of unique packTitle values with

[myCards valueForKeyPath:@"@distinctUnionOfObjects.packTitle"];

这将为您提供 packTitle myCards 集合中的值。如果您想要对Core Data存储中的所有卡进行此操作,则必须对所有运行查询,然后应用此收集操作。

which will give you the distinct set of packTitle values in the myCards collection. If you want this for all cards in the Core Data stores, you will have to run a query for all cards, then apply this collection operation.

另一种方法是创建一个 PackInformation 实体,或某些包含 title 属性。然后,您可以在数据存储中只有这些实体,从适当的包实体引用它们。

The alternative is to make a PackInformation entity, or some such which contains a title property. You can then have only 3 of these entities in the data store, referencing them from the appropriate pack entities. It's trivial to fetch all three (or whatever the final number is) and get their titles.

正如其他人所说,如果你想要做的是从根本上报告从关系数据集,你可以更好地使用直SQLite。这一切都取决于你从Core Data获得多少其他收益。

As others have said, if what you're trying to do is fundamentally reporting from a relational data set, you may better off going with straight SQLite. It all depends on how much other benefit you get from Core Data.

这篇关于NSPredicate等价于SQL的GROUP BY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆