将双值保存到核心数据有时可以节省完全错误的值

时间:2014-02-26 15:50:45

标签: ios objective-c core-data

我正在通过2个双倍值(distance,distanceToClosePoint)更新核心数据实体。 一些数据以错误的值保存,结果在我的应用程序中完全混乱。

首先:

- (void)updateTrapDistance:(double)distance trapID:(int)trapID distanceToClosePoint:(double)distanceToClosePoint
{
    NSManagedObjectContext *context = generateManagedObjectContext();

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"trapID.intValue==%i", trapID];
[fetchRequest setPredicate:predicate];

NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects == nil || fetchedObjects.count == 0) {
    NSLog(@"%s error saving: %@\n%@", __PRETTY_FUNCTION__, error.localizedDescription, error.userInfo);

    return;
}

CoreDataAllTraps *trap = fetchedObjects.firstObject;
[trap setDist:[NSNumber numberWithInt:distance]];
[trap setDist_to_close_point:[NSNumber numberWithInt:distanceToClosePoint]];

if(![context save:&error]) {
    NSLog(@"%s error saving: %@\n%@", __PRETTY_FUNCTION__, error.localizedDescription, error.userInfo);
    return;
}

NSLog(@"id: %d, distance: %f = %f distanceToClosePoint", trapID, distance, distanceToClosePoint);
NSLog(@"id: %d, dist: %f, dist_to_close_point: %f\n\n", trapID, trap.dist.doubleValue, trap.dist_to_close_point.doubleValue);

}

打印哪些:

2014-02-26 17:40:47.965 Cellular Radar[769:5b0f] id: 32, distance: 130881.349358 = 132445.944382 distanceToClosePoint
2014-02-26 17:40:47.972 Cellular Radar[769:5b0f] id: 32, dist: -191.000000, dist_to_close_point: 1373.000000

然后阅读它:

- (NSMutableArray*)getCloseXTraps:(int)numberOfTraps
{
    NSManagedObjectContext *context = generateManagedObjectContext();

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"dist_to_close_point.doubleValue > %d", 0];
    [fetchRequest setPredicate:predicate];

    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE_TO_CLOSE_POINT ascending:YES];
    [fetchRequest setSortDescriptors:@[sortDescriptor]];

    // Limit the restlus to specific number
    [fetchRequest setFetchLimit:numberOfTraps];

    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil || fetchedObjects.count == 0) {
        NSLog(@"%s error: %@", __PRETTY_FUNCTION__, error.localizedDescription);
        return nil;
    }
    else {
        NSMutableArray *newArray = [NSMutableArray new];
        for (CoreDataAllTraps *trap in fetchedObjects) {
            NSLog(@"id: %d, dist_to_close_point: %f, dist: %f", trap.trapID.integerValue, trap.dist_to_close_point.doubleValue, trap.dist.doubleValue);
            Traps *singleTrap = [self convertFromCoreData:trap];
            [newArray addObject:singleTrap];
        }
        return newArray;
    }
}

打印哪些:

2014-02-26 17:40:54.973 Cellular Radar[769:5b0f] id: 32, dist_to_close_point: 1373.000000, dist: -191.000000

生成NSManagedObjectContext:

FOUNDATION_EXPORT NSManagedObjectContext *generateManagedObjectContext()
{
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator;

    if ([NSThread isMainThread])    { [context setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy]; }
    else                            { [context setMergePolicy:NSMergeByPropertyStoreTrumpMergePolicy]; }

    return context;
}

我必须说,并非所有的双重值都被保存错误,但其中一些并且这足以造成混乱。

这里有什么问题?

1 个答案:

答案 0 :(得分:7)

我假设您已定义disttrap.dist_to_close_point Core Data模型检查器中的属性为 “整数16”。在这种情况下,Core Data访问器方法(静默地)截断 所有值都是16位。

例如,如果distance = 130881.349358[NSNumber numberWithInt:distance] 表示整数130881 = 0x1FF41。截断到16位给出 0xFF41 = -191,这是你观察到的。

将类型更改为“Double”可以解决问题。

您还应该使用numberWithDouble:distance(或@(distance),如Dan建议的那样)代替numberWithInt:distance进行分配, 避免将值舍入为整数。