我有一个名为messages
的实体,其中包含以下属性:
- > message_id
,message_from
,message_to
,message_body
,date_created
。
我想像WhatsApp聊天一样为每个用户提取最后一个message
。
我找到了MySQL
的以下代码,但不知道如何将其与NSPredicates
一起使用:
SELECT *
FROM messages m1
WHERE date_created = (SELECT MAX(m2.date_created)
FROM messages m2
WHERE m1.message_from = m2.message_from
AND m1.message_to = m2.message_to)
有人可以帮助我使用NSPredicate
从核心数据中获取每个用户的最后一条消息吗?
答案 0 :(得分:0)
首先,您需要一个提取所有消息和所有用户的方法。为简单起见,请将其放入AppDelegate.m中。请注意,getAllMessages通过将数据提取为NSDictionary来获得唯一结果,根据定义,它不允许重复键
-(NSArray*)getAllUsers
{
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Setting Entity to be Queried
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
inManagedObjectContext:self.managedObjectContext];
fetchRequest.resultType = NSDictionaryResultType;
fetchRequest.returnsDistinctResults = YES;
[fetchRequest setEntity:entity];
[fetchRequest setPropertiesToFetch:@[@"userId"]];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date_created" ascending:NO]];
NSError* error;
// Query on managedObjectContext With Generated fetchRequest
NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
// Returning Fetched Records
return fetchedRecords;
}
-(NSArray*)getAllMessages
{
// initializing NSFetchRequest
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
//Setting Entity to be Queried
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Message"
inManagedObjectContext:self.managedObjectContext];
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date_created" ascending:NO]];
[fetchRequest setEntity:entity];
NSError* error;
// Query on managedObjectContext With Generated fetchRequest
NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
// Returning Fetched Records
return fetchedRecords;
}
然后,您可以通过执行以下操作为NSMutableArray中的每个用户提取并放置最后一条消息:
AppDelegate * appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSMutableArray * arrayUsers = [NSMutableArray arrayWithArray:[appDelegate getAllUsers]];
NSMutableArray * arrayMessages = [NSMutableArray arrayWithArray:[appDelegate getAllMessages]];
NSMutableArray * lastMessageForEachUser = [NSMutableArray array];//on this array you get the results
for (NSDictionary * dict in arrayUsers)
{
NSNumber * userId = [dict objectForKey:@"userId"];
NSPredicate * pr = [NSPredicate predicateWithFormat:@"userId == %@",userId];
NSArray * results = [arrayMessages filteredArrayUsingPredicate:pr];
Message * lastMessage = results.count>0 ? [results objectAtIndex:0] : nil;
[lastMessageForEachUser addObject:lastMessage];
}