我在 iOS-CoreData 上下文中创建有效的 NSPredicate 时遇到问题。该表包含所有好友的所有消息。我需要得到每个好友的最新消息:
我尝试过使用 DBVisualizer,我需要以下 SQL(工作正常)
/* for testing with a db tool like DbVisualizer
select ZBAREJIDSTR,ZBODY, ZTIMESTAMP
from ZXMPPMESSAGEARCHIVING_MESSAGE_COREDATAOBJECT
group by ZBAREJIDSTR
having max(ZTIMESTAMP)
order by ZTIMESTAMP desc;
*/
以下代码因“无法解析格式字符串”而失败,我找不到适合我的示例。
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
NSManagedObjectContext *moc = [[Utilities chatManagerFromAppDelegate] managedObjectContext_messageArchiving];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSAttributeDescription* bodyDesc = [entity.attributesByName objectForKey:@"body"];
NSAttributeDescription* barJidStrDesc = [entity.attributesByName objectForKey:@"barJidStr"];
NSAttributeDescription* timestampDesc = [entity.attributesByName objectForKey:@"timestamp"];
NSPredicate *predicateMaxTimestamp = [NSPredicate predicateWithFormat:@"@max.timestamp"];
NSSortDescriptor *sortDescriptorTimestampDesc = [[NSSortDescriptor alloc] initWithKey:@"timestamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptorTimestampDesc, nil];
[fetchRequest setEntity:entity];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:barJidStrDesc, bodyDesc, timestampDesc, nil]];
[fetchRequest setPropertiesToGroupBy:[NSArray arrayWithObject:bodyDesc]];
[fetchRequest setHavingPredicate: predicateMaxTimestamp];
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setFetchBatchSize:10];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:moc
sectionNameKeyPath:nil
cacheName:nil];
....
实际上我也很欣赏其他替代方案,因为我需要更新底层模型([fetchedResultsController setDelegate:self];),它不适用于 NSDictionaryResultType(但 NSDictionaryResultType 对于 group by 是必需的)。