NSPredicate为核心数据中的每个会话获取最后一条消息

时间:2016-01-29 07:50:44

标签: objective-c core-data nspredicate

我有一个名为messages的实体,其中包含以下属性:   - > message_idmessage_frommessage_tomessage_bodydate_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从核心数据中获取每个用户的最后一条消息吗?

1 个答案:

答案 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]; 
}