我正在使用名为CrumbPoint
存储纬度和经度的核心数据实体,它指向(与)另一个名为HRRecord
. CrumbPoint 是这样创建的:
CrumbPoint *crumbPoint = [NSEntityDescription insertNewObjectForEntityForName:@"CrumbPoint"
inManagedObjectContext:context];
crumbPoint.lat = [NSNumber numberWithFloat:lat];
crumbPoint.lon = [NSNumber numberWithFloat:lon];
crumbPoint.velocity = [NSNumber numberWithFloat:velocity];
crumbPoint.date = [NSDate date];
// Since this use search query, always refresh from DB
// The following fetch using NSFetchRequest when the record is available.
HrRecord * hr = [HRRecord hrRecordWithTitle:title inManagedObjectContext:context];
crumbPoint.inRecord = hr;
HrRecord 有一个名为的字段distance
,只要设备有位置更新,我就需要更新该字段。(我正在跟踪用户慢跑)。对于每个位置更新,CrumbPoint
都会创建一个新的,它指向HrRecord
相同的慢跑会话。需要计算先前位置和新位置之间的新距离并且HrRecord
需要更新距离。
但是我的问题是每次我得到 HrRecord (也许这是一个糟糕的设计,但我每次都NSFetchRequest
用来查询新的位置更新。)HrRecord
现在当我尝试更新时:
HrRecord * hr = crumbPoint.inRecord;
float oldDistance = [hr.distance doubleValue];
// code to calculate distance here, then, update
hr.distance = [NSNumber numberWithDouble: newDistanceUpdate];
hr.distance
更新前总是 0,即使每次更新后我都可以打印出新值。我尝试发送save
到托管对象上下文,但它似乎也不起作用。这是为什么?
编辑:这是插入的代码。也许该错误与保存无关,在保存上下文后,我尝试拉出记录[HrRecord HrRecordWithTitle:title inManagedObjectContext:context]
并为该轮更新距离。但是下次位置更新时,由于某种原因,它再次为 0。我必须检查更多代码。:/
+(HrRecord *)HrRecordWithTitle: (NSString *)title
inManagedObjectContext:(NSManagedObjectContext *)context
{
HrRecord * record = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"HrRecord"];
request.predicate = [NSPredicate predicateWithFormat:@"title = %@", title];
NSSortDescriptor * sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError * error = nil;
NSArray * records = [context executeFetchRequest:request error:&error];
if (!records || records.count > 1) {
// Nil, or more than one is an error
} else if (records.count == 0) {
// Create a new record with starting duration of 0
record = [NSEntityDescription insertNewObjectForEntityForName:@"HrRecord" inManagedObjectContext:context];
record.title = title;
record.duration = @0.0;
record.distance = @0.0;
record.date = [NSDate date];
} else { // Recrod exists, exactly one
record = [records lastObject];
// update duration
record.duration = @([record.duration intValue] + 1);
}
return record;
}