核心数据 - 获取对象数组的最后一个对象?
问题描述:
使用下面的代码,我从Core Data中获取一组电子邮件。我将一个emailId数组作为谓词传递给fetch,并返回每个emailIds的所有电子邮件。核心数据 - 获取对象数组的最后一个对象?
但是,我只需要谓词中每个emailIds的最后一个对象(或最后一封电子邮件)。目前,我使用此提取的输出并使用单独的排序来过滤我想要的对象。不过,我希望在这个抓取中进行过滤。有没有办法做到这一点?
- (NSFetchedResultsController *)getLatestEmail:(NSArray *)emailId
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"email_id IN %@", emailId];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Emails"
inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"last_update_timestamp" ascending:NO];
NSArray *sortDescriptors = @[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:self.context
sectionNameKeyPath:nil
cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.emailFetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.emailFetchedResultsController performFetch:&error])
{
NSLog(@"getLatestEmail failed %@, %@", error, [error userInfo]);
}
NSArray *emails = [[self.context executeFetchRequest:fetchRequest error:&error] mutableCopy];
return _emailFetchedResultsController;
}
我尝试添加.lastobject
到[[self.context executeFetchRequest:fetchRequest error:&error] mutableCopy]
,但没有奏效。我也找不到任何文件表明这是可能的。不过,我确信,有人会尝试过,并希望听到他们的意见。
答
反转您的排序描述符,然后将批量大小设置为1,并将偏移量设置为零。
我不认为你可以使用核心数据。你最好采用返回的集合并使用@max谓词。看看https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/CollectionOperators.html –
我可能会离开这里,但如果你可以通过电子邮件获得第一条记录[0 ],最后的记录不会是电子邮件[-1]。这似乎适用于几种编程语言。 – StephenCollins