我有一个包含步骤和时间戳的数据库。每个记录可以例如50个步骤和时间戳。我试图用NSPredicate过滤这些记录,按小时过滤以显示条形图,然后显示当天的“总数”。
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:YES];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Activity"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"(timestamp >= %@) AND (timestamp <= %@)", from, to];
fetchRequest.sortDescriptors = @[descriptor];
NSArray *activities = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
从日期和到日期提供如下:
2015-03-07 05:00:00 +0000 - 2015-03-07 05:59:59 +0000
结果是记录:
Timestamp: 2015-03-07 05:59:53 +0000, Steps: 0 2015-03-07 05:00:00 +0000 - 2015-03-07 05:59:59 +0000
问题是,随着更多步骤条目的添加,随着条目的增长,“总”计数似乎会增加,加倍,增加三倍等。似乎谓词可能会根据时间戳重复计算某些记录。
- (void)getSteps
{
__block NSInteger _numberOfSteps = 0;
__block NSInteger _numberOfRest = 0;
__block NSInteger _numberOfLow = 0;
__block NSInteger _numberOfHigh = 0;
__weak __typeof(self)weakSelf = self;
[_activityManager queryActivityStartingFromDate:startDate toDate:endDate toQueue:[NSOperationQueue mainQueue] withHandler:^(NSArray *activities, NSError *error)
{
for (NSInteger i = 0; i < activities.count; i++)
{
CMMotionActivity *activity = activities[i];
NSTimeInterval duration = 0.0;
if (i < activities.count-1)
{
CMMotionActivity *nextActivity = (CMMotionActivity *)activities[i+1];
duration = [nextActivity.startDate timeIntervalSinceDate:activity.startDate];
}
else
duration = [endDate timeIntervalSinceDate:activity.startDate];
if (activity.walking)
_numberOfLow += round(duration);
else if (activity.running)
_numberOfHigh += round(duration);
else
_numberOfRest += round(duration);
}
if (activities.count == 0)
_numberOfRest = (NSInteger)[weakSelf reportingInterval];
if ( [endDate timeIntervalSinceDate:startDate] > [self reportingInterval] )
_numberOfRest = [endDate timeIntervalSinceDate:startDate];
[_stepCounter queryStepCountStartingFrom:startDate to:endDate toQueue:[NSOperationQueue mainQueue] withHandler:^(NSInteger numberOfSteps, NSError *error)
{
_numberOfSteps = numberOfSteps;
// Nothing special, no calculations here, just creates record
[self addSteps:@{@"timestamp":[ActivityEngine dateSpan:CDPDateSpanLocalTime],
@"steps":[NSString stringWithFormat:@"%ld", (long)_numberOfSteps],
@"rest":[NSString stringWithFormat:@"%ld", (long)_numberOfRest],
@"low":[NSString stringWithFormat:@"%ld", (long)_numberOfLow],
@"high":[NSString stringWithFormat:@"%ld", (long)_numberOfHigh]
}];
}];
}];
}
答案 0 :(得分:1)
在您的代码中,您将遍历所有活动并查询特定日期范围。如果你反复这样做,你的步数肯定会加倍和三倍等。
确保以增量方式更新数据。出错的原因是您调用getSteps
函数的方式和频率。也许您应该跟踪已经存储的日期范围,并从下一个查询中排除这些范围。