我的核心数据表是这样的:
我想收到每个发件人的最新消息。所以结果应该是这样的:
这是我的代码:
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];
我将获取所有排序的数据(最新消息优先)。 但是我怎样才能根据发件人获得唯一的值(value)呢?所以只有每个发件人的最新消息?
基本上我需要这个 SQL 的等价物:
SELECT message, sender, MAX(time) as maxTime FROM myTable GROUP BY sender;
最佳答案
获取消息字段是困难的部分。
基本上,如果您使用分组依据,您只能获取分组依据(发送者)中的属性和带有表达式(时间)的属性。
要获取所有其他值,您需要使用获取的值(发件人和时间)并执行另一次获取以从核心数据中获取它。
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];
}
关于ios - 如何根据核心数据中的一个字段获得不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44265559/