我将 Core Data 用于 iPhone 应用程序。 存在具有“开始”和“持续时间”属性的“航类”实体。 航类列在分页 View 中,我需要在其中计算每页持续时间和持续时间汇总总和。 在 native 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 的汇总总和。 等等..
现在是问题:
我将如何使用 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;
最佳答案
如您所说,在获取请求上设置的限制和偏移量将应用于结果,并且 NSExpression
在这种情况下将无法正常工作。在返回的对象被获取请求偏移和限制之后,您可以使用 collection operator 对返回的对象进行操作。而不是 NSExpression
,例如:
NSNumber *durationSum = [objects valueForKeyPath:@"@sum.duration"];
关于ios - 相当于 sqlite 查询的核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8581999/