2011-12-20 101 views
2

我使用核心数据为iPhone应用程序。 “Flight”实体具有“开始”和“持续时间”属性。 航班在分页视图中列出,我需要总结每页的持续时间和持续时间汇总总和。 在下述溶液中本地sqlite的工作原理:核心数据相当于sqlite查询

select sum(pg.zduration) from (select zduration,zstart from zflight order by zstart limit %i,%i) as pg",offset,limit 
  • 所以第一页上,为5的页面大小,我得到持续时间之和相同的汇总时间与偏移= 0,上限= 5。
  • 在第二页上,我得到了offset = 5和limit = 5的持续时间总和。累计和与offset = 0和limit = 10。 等等..

现在的问题:
我将如何解决与核心数据,NSExpression,NSExpressionDescription和NSFetchRequest而不是SQLite的?当然,我不希望加载在内存中的所有飞行物体......

所以我能caculate所有航班的时间:

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

正如你所说,限制和偏移设置在这种情况下,获取请求将应用于结果,并且NSExpression将无法​​正常工作。你可以在返回的对象进行操作,他们已经被抵消,并通过读取请求的限制后,使用collection operator而不是NSExpression,例如:

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