iOS 核心数据更新到未保存的数据



我正在使用名为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]和距离 IS 的记录。但是下次位置更新出现时,由于某种原因,它再次为 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;
}
您使用

什么托管对象上下文?您应该使用在当前线程中创建的上下文。

最新更新