gpt4 book ai didi

ios - CoreData 重复结果,时间戳谓词

转载 作者:行者123 更新时间:2023-11-29 02:14:19 25 4
gpt4 key购买 nike

我有一个包含步骤和时间戳的数据库。例如,每条记录可能有 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

问题是,随着添加的steps 条目越多,“总”计数似乎会随着条目的增长而增加,增加一倍、三倍等。看来谓词可能根据时间戳重复计算某些记录。

从手机获取步数

- (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]
}];
}];
}];
}

如何确保没有记录被重复计算?

最佳答案

在您的代码中,您遍历所有事件并查询特定日期范围。如果你反复这样做,你的步数肯定会增加一倍和三倍,等等。

确保以增量方式更新数据。错误的原因是您调用 getSteps 函数的方式和频率。或许您应该跟踪已存储的日期范围并从下一个查询中排除这些范围。

关于ios - CoreData 重复结果,时间戳谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com