iOS Core数据更新为未保存的数据

时间:2013-10-21 09:20:18

标签: ios objective-c core-data

我正在使用名为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发送到托管对象上下文,但它似乎也不起作用。那是为什么?

编辑: 这是插入的代码。也许这个bug不是关于保存,在上下文保存之后我尝试用[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;
}

1 个答案:

答案 0 :(得分:0)

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