如何根据核心数据中的一个字段获得不同的结果

时间:2017-05-30 14:53:36

标签: ios objective-c core-data nspredicate

我的核心数据表是这样的:

enter image description here

我想从每位发件人处获取最新消息。所以结果应该是:

enter image description here

这是我的代码:

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyCoreDataObject" inManagedObjectContext:moc];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"MESSAGE <> ''"];

    request.predicate = predicate;
    NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"TIME" ascending:NO];
    NSArray *sortDescriptors = @[sd1];
    [request setSortDescriptors:sortDescriptors];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *msgs = [moc executeFetchRequest:request error:&error];

我将获得所有排序数据(最新消息)。 但是如何根据发件人获得唯一值?那么每个发件人只有最新消息?

基本上我需要相当于这个SQL:

SELECT message, sender, MAX(time) as maxTime FROM myTable GROUP BY sender;

1 个答案:

答案 0 :(得分:1)

获取消息字段是困难的部分。

基本上,如果您使用group by,则只能通过(sender)和带有表达式(time)的属性获取组中的属性。

要获取所有其他值,您需要使用获取的值(发送方和时间)并执行另一次提取以从核心数据中获取它。

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyCoreDataObject" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"message <> ''"];

request.predicate = predicate;
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:NO];
NSArray *sortDescriptors = @[sd1];
[request setSortDescriptors:sortDescriptors];
[request setEntity:entityDescription];

NSExpressionDescription *timestampExp = [[NSExpressionDescription alloc] init];
[timestampExp setExpression:[NSExpression expressionWithFormat:@"@max.time"]];
[timestampExp setName:@"time"];
[timestampExp setExpressionResultType:NSDateAttributeType];

[request setSortDescriptors:sortDescriptors];
[request setEntity:entityDescription];
[request setResultType:NSDictionaryResultType];
[request setPropertiesToGroupBy:[NSArray arrayWithObject:@"sender"]];
[request setPropertiesToFetch:[NSArray arrayWithObjects:@"sender", timestampExp, nil]];

NSError *error;
NSArray *msgs = [moc executeFetchRequest:request error:&error];
for (NSDictionary *msg in msgs) {
    request = [[NSFetchRequest alloc] init];
    predicate = [NSPredicate predicateWithFormat:@"message <> '' and sender = %@ and time = %@ ", msg[@"sender"], msg[@"time"]];

    request.predicate = predicate;
    [request setSortDescriptors:sortDescriptors];
    [request setEntity:entityDescription];
    NSDictionary *myMessage = [moc executeFetchRequest:request error:&error][0];

}