ios - 将双重值(value)保存到核心数据有时会保存完全错误的值(value)

标签 ios objective-c core-data

我正在用 2 个 double 值(距离、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;
}

我必须说,并不是所有的 double 值都被错误地保存了,但其中一些已经足以造成一团糟了。

这里有什么问题吗?

最佳答案

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

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

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

您还应该使用 numberWithDouble:distance(或 Dan 建议的 @(distance))而不是 numberWithInt:distance 进行分配, 以避免将值四舍五入为整数。

关于ios - 将双重值(value)保存到核心数据有时会保存完全错误的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22046448/

相关文章:

ios - UIView动画选项没有效果

iphone - 如何从 iOS 应用程序发送 POST XML?

iOS - 调用方法 : [self. navigationController pushViewController : animated:], 屏幕全黑

ios - 离开 View 时停止异步 block 请求(AFNetworking;iOS)

ios - 如何获取 GMSPolygon 中的 GMSMarker

objective-c - map 叠加层中的文本框/自定义 View 中的文本框以显示在 map 上

objective-c - 将 C 与 Objective C 混合

ios - Core Data 中如何有效处理大数据集?

iOS URLForUbiquityContainerIdentifier 在某些设备上返回 nil

iphone - 对核心数据对象进行分组