核心数据等效于sqlite查询

时间:2011-12-20 21:07:26

标签: ios sqlite core-data

我将Core Data用于iPhone应用程序。 飞行"飞行"带有" start"的实体和#34;持续时间"属性。 这些航班列在分页视图中,我需要将每页的持续时间和持续时间汇总总和相加。 在原生sqlite下面的解决方案工作:

select sum(pg.zduration) from (select zduration,zstart from zflight order by zstart limit %i,%i) as pg",offset,limit
  • 因此,在第一页上,页面大小为5时,我得到持续时间总和和相同的汇总持续时间,其中offset = 0且limit = 5.
  • 在第二页上,我得到持续时间和,其中offset = 5,limit = 5。累加和与offset = 0和limit = 10。 等等..

现在问题:
我如何使用Core Data,NSExpression,NSExpressionDescription和NSFetchRequest而不是sqlite来解决这个问题?当然,我不想在内存中加载所有的飞行物......

所以我能够计算所有航班的持续时间:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flight" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];

[request setResultType:NSDictionaryResultType];

NSSortDescriptor *startSortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"start"
                                                                    ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:startSortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];

request.fetchOffset=onPage*pageSize;//does not help, cause offset and limit are applied to the result
request.fetchLimit=pageSize;//does not help, cause offset and limit are applied to the result

NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"duration"];    
NSExpression *sumExpression = [NSExpression expressionForFunction:@"sum:" arguments:[NSArray arrayWithObject:keyPathExpression]];

// Create an expression description using the minExpression and returning a date.
NSExpressionDescription *expressionDescription1 = [[NSExpressionDescription alloc] init];    
[expressionDescription1 setName:@"durationSum"];
[expressionDescription1 setExpression:sumExpression];
[expressionDescription1 setExpressionResultType:NSInteger64AttributeType];


[request setPropertiesToFetch:[NSArray arrayWithObjects:expressionDescription1,nil]];

// Execute the fetch.
NSError *error = nil;
NSArray *objects = [self.managedObjectContext executeFetchRequest:request error:&error];
if(error!=nil){
    [NSException raise:@"Sum Page Duration failed" format:@"%@ Error:%@", [[error userInfo] valueForKey:@"reason"],error];        
}

if (objects!=nil && [objects count] > 0) {
    return (NSNumber*)[[objects objectAtIndex:0] valueForKey:@"durationSum"];
}
return 0;

1 个答案:

答案 0 :(得分:1)

正如您所说,在获取请求上设置的限制和偏移量将应用于结果,NSExpression在这种情况下将无法正常工作。您可以使用collection operator而不是NSExpression对已返回的对象进行操作,这些对象在被偏移并受到获取请求限制后,例如:

NSNumber *durationSum = [objects valueForKeyPath:@"@sum.duration"];