具有复杂谓词的NSFetchedResultsController

时间:2016-03-02 10:03:27

标签: ios core-data nspredicate nsfetchedresultscontroller

我正在使用UICollectionView开发应用 它是按日期安排的活动集合。我正在使用NSFetchedResultsController从数据库中获取数据。但我需要获取当前和未来的事件+ 2个过去的事件。 对于NSFetchRequest我正在使用NSCompoundPredicate

NSPredicate *nextPredicate = [NSPredicate predicateWithFormat: @"startAt >= %@", [NSDate date]];
NSPredicate *previousPredicate = [NSPredicate predicateWithFormat:@"startAt < %@", [NSDate date]];
NSCompoundPredicate *resultPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: @[nextPredicate, previuosPredicate]];
fetchRequest.predicate = resultPredicate;

我不知道如何限制previousPredicate只收到2件物品。

1 个答案:

答案 0 :(得分:1)

如果您知道当前事件的日期,则创建一个方法,该方法返回要获取的最后一个事件的日期,然后将主NSFetchRequest上的谓词设置为该日期。

 -(NSDate *)dateOfPastEvent{
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:_mainContext];
    [request setEntity:entity];

    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"startAt" ascending:NO];
    [request setSortDescriptors:@[sortDesc]];

    NSError *error = nil;
    NSArray *array = [_mainContext executeFetchRequest:request error:&error];


    __block NSDate *pastEventDate;

    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){

        if ([obj valueForKey:@"startAt"] == currentEventDate) {
            if (array.count >= idx+2) {
                pastEventDate = [[array objectAtIndex:idx+2] valueForKey:@"startAt"];
                *stop = YES;
            }

        }
    }];


    return pastEventDate;

}

现在为上述返回日期设置谓词

  NSFetchRequest *requestForController = [[NSFetchRequest alloc]init];
  NSEntityDescription *entity = [NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:_mainContext];
    [requestForController setEntity:entity];

  NSPredicate *predicate = [NSPredicate predicateWithFormat: @"startAt >= %@", [self dateOfPastEvent]];