Setting the value of a double attribute on NSManagedObject

微笑、不失礼 提交于 2020-01-11 09:34:11

问题


I am trying to implement a maps feature on my application. However to I would like the latitude and longitude be passed into the map from an object that is stored in core data. However I am having problem setting the initial value on the object when I start my application. I have tried 2 different ways so far and each and error I receive is "Sending 'double to a parameter of incompatible type 'id'. Any help would be very appreciated.

NSManagedObject *room = [NSEntityDescription insertNewObjectForEntityForName:@"Room" inManagedObjectContext:context];

    double myLatitude = -1.228087;
    double myLongitude = 52.764397;

    [room setValue:@"H001" forKey:@"code"];
    [room setValue:@"This is a description" forKey:@"roomDescription"];
    [room setValue:myLatitude forKey:@"longitude"];
    [room setValue:myLatitude forKey:@"latitude"];

回答1:


NSManagedObject attributes need to be objects, but double is a primitive C type. The solution is to wrap the doubles in an NSNumber:

[room setValue:[NSNumber numberWithDouble:myLongitude] forKey:@"longitude"];
[room setValue:[NSNumber numberWithDouble:myLatitude] forKey:@"latitude"];



回答2:


You should wrap your double as an NSNumber:

[NSNumber numberWithDouble:myDouble]

NSManagedObject setValue:forKey: requires an id for it's value. The double is a primitive.




回答3:


This answer tells you how to store a float in Core Data. Here it is for a double

[room setValue:[NSNumber numberWithDouble:myLatitude] forKey:@"latitude"];


来源:https://stackoverflow.com/questions/9886160/setting-the-value-of-a-double-attribute-on-nsmanagedobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!