无法在NSManagedObject中存储双精度数

时间:2014-08-29 13:09:06

标签: ios objective-c xcode core-data xcode6

当尝试在对象中存储double时,我收到错误

 error Sending 'double' to parameter of incompatible type 'id'

我的代码是:

    NSManagedObjectContext *context = [self managedObjectContext];
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts"     inManagedObjectContext:context];

    [newDevice setValue:longitudes forKey:@"longitude"];
    [newDevice setValue:latitudes  forKey:@"latitude"];


setValue:longitudes 
经度是双重的。

3 个答案:

答案 0 :(得分:2)

您需要使用NSNumber来存储双倍值。

NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts"     inManagedObjectContext:context];

[newDevice setValue:@(longitudes) forKey:@"longitude"];
[newDevice setValue:@(latitudes)  forKey:@"latitude"];

所以它应该有用。

你也可以写:

NSNumber *longitudesNumber = [NSNumber numberWithDouble:longitudes];
NSNumber *latitudesNumber = [NSNumber numberWithDouble:latitudes];
[newDevice setValue: longitudesNumber forKey:@"longitude"];
[newDevice setValue: latitudesNumber   forKey:@"latitude"];

更好地理解:)

要表明,你可以使用:

NSNumber *number = ...(your object);

label.text = [NSString stringWithFormat:@"%@", number];
label.text = [NSString stringWithFormat:@"%f", [number doubleValue]];

答案 1 :(得分:1)

你可以这样做

[newDevice setValue:[NSNumber numberWithDouble:longitudes] forKey:@"longitude"];
[newDevice setValue:[NSNumber numberWithDouble:latitudes]  forKey:@"latitude"];

答案 2 :(得分:0)

您的代码:

[newDevice setValue:longitudes forKey:@"longitude"];

...使用key-value coding method设置值,键值编码方法需要值对象。这是setValue:forKey:的方法签名:

- (void)setValue:(id)value forKey:(NSString *)key

发生异常是因为您将double传递给value参数。您的NSManagedObject子类可以 - 并且应该 - 使用标量而不是NSNumber来表示双精度数,如果不首先将值包装在NSValue类中,则无法使用setValue:forKey:。但是,您可以使用传统表示法或点表示法来设置值为double:

[newDevice setLongitude:longitudes];

newDevice.longitude = longitudes;