将浮点数发送到不兼容类型 id 的参数

Sending float to parameter of incompatible type id

我正在创建一个按钮,该按钮使用核心数据来保存点注释的名称、x 坐标和 y 坐标。我可以成功保留名称,但是当我尝试保存坐标时,我一直收到此错误。我已经记录了正确的数据,但我似乎无法保存它。

当我尝试为 newPOI 设置值时,我收到一条错误消息: 将 'float' 发送到不兼容类型的参数 'id'。

在数据模型中,属性设置为浮动。 self.latitude 和 self.longitude 是 float 类型。

我的方法有点粗糙,因为我对此比较陌生,但如果您能给我有关错误的任何反馈,我将不胜感激。下面是我的方法代码。我不明白 'id' 在这里发挥作用。

-(void) saveSelectedPoiName:(NSString *)name withY:(float)yCoordinate withX:(float)xCoordinate{
    self.pointFromMapView = [[MKPointAnnotation alloc] init];
    self.annotationTitleFromMapView = [[NSString alloc] init];

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    self.annotationTitleFromMapView = name;
    self.latitude = yCoordinate;
    self.longitude = xCoordinate;

    NSEntityDescription *entityPOI = [NSEntityDescription entityForName:@"POI" inManagedObjectContext:context];
    NSManagedObject *newPoi = [[NSManagedObject alloc] initWithEntity:entityPOI insertIntoManagedObjectContext:context];
    //create new POI record
    [newPoi setValue:name forKey:@"name"];
    [newPoi setValue:yCoordinate forKey:@"yCoordinate"]; <---error happens here for yCoordinate.

    NSError *saveError = nil;

    if (![newPoi.managedObjectContext save:&saveError]) {
        NSLog(@"Unable to save managed object");
        NSLog(@"%@, %@", saveError, saveError.localizedDescription);
    }
}

Core Data 中的 NSManagedObject 属性必须是一个对象,而不是原始类型。在这种情况下,我们的 yCoordinate 是 float 类型。为了 setValue: 浮点类型,您必须首先将值包装在 NSNumber 中。

[newPoi setValue:[NSNumber numberWithFloat:someFloat] forKey:@"yCoordinate"];

对比

[newPoi setValue:someFloat forKey:@"yCoordinate"];