复杂的CoreData查询(也需要SQL语法)?

时间:2011-09-09 10:31:43

标签: ios sqlite core-data nspredicate

我有两个实体:

Performance.start (NSDate)    Location.coordinates
Performance.end   (NSDate)    Location.name_extern
Performance.location   <<-->  Location.performances

我的NSFetchedResultsController设置UITableView,代码如下:

[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                    managedObjectContext:self.managedObjectContext 
                                      sectionNameKeyPath:@"location.name_extern" 
                                               cacheName:nil];

因此,数据按位置(名称)分为几个部分。

现在我有一个selectedTime类型的变量NSDate,并且想要获取(如果可能的话,只需一次获取)以下内容:

  1. 每个位置仅有2个演出:
    • 正在运行的效果(selectedTime BETWEEN {start, end})
    • 将在所选时间运行的性能之后启动的性能
  2. 我真的迷失在这里: - /即使你可以给我这样一个获取/查询的SQL语句,我至少知道要走向哪个方向..

2 个答案:

答案 0 :(得分:0)

使用SQL,您可以尝试这样的事情:

SELECT *
FROM Performance p, (
    SELECT *
    FROM Performance
    WHERE start <= selectedTime AND end >= selectedTime
    ORDER BY start ASC
    LIMIT 1
) AS p1
WHERE p.start >= p1.start
ORDER BY p.start ASC
LIMIT 2

虽然您必须决定如何处理当时没有性能运行的情况。

使用核心数据,您只需按开始日期(ASC)订购它们,使用start&lt; = selectedTime,返回2结果,以及(在代码中?)检查第一个结果的结束日期是否为&gt; = selectedTime

答案 1 :(得分:0)

Duh ..我想我找到了最终解决方案..

获取非常简单:

NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"Performance" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] 
                          initWithKey:@"location.name_extern" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] 
                           initWithKey:@"start" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort1,sort2,nil]];

[fetchRequest setFetchBatchSize:20];

NSFetchedResultsController *theFetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
                                    managedObjectContext:self.managedObjectContext 
                                      sectionNameKeyPath:@"location.name_extern" 
                                               cacheName:nil];

使用以下谓词:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"end > %@",selectedTime];

[fetchRequest setPredicate:predicate];

以下是我解决“每个位置/部分只有2个”的部分:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    if (selectedTime == nil)
    {
        return [sectionInfo numberOfObjects];
    }
    else
    {
        if ([sectionInfo numberOfObjects] > 2)
        {
            return 2;
        }
        else
        {
            return [sectionInfo numberOfObjects];
        }
    }
}

感谢André尝试!

相关问题