ioscore-datamapkitcllocationmkmapitem

Storing CLLocationCoordinates in Core Data


I've encountered an issue when storing a MKMapItem that I was able to resolve by looking at compiler warnings, but I don't understand why I was able to resolve it or if I utilized "best practices".

I have an Object model that stores latitude and longitude coordinates from an MKMapItem separately as doubles in an NSManagedObject. When I go to Editor\Create NSManagedObject Subclass and create the my class, the header looks like this:

@class LocationCategory;

@interface PointOfInterest : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * address;
// Xcode spat out NSNumber instead of the double specified in the model setup screen
@property (nonatomic, retain) NSNumber * latitude;
@property (nonatomic, retain) NSNumber * longitude;
@property (nonatomic, retain) NSString * note;
@property (nonatomic, retain) LocationCategory *locationCategory;

@end

All was well until I tried to add an object to my managedObjectContext I got these warnings:

Assigning to 'NSNumber *' from incompatible type 'CLLocationDegrees' (aka 'double')

on these lines:

newPOI.latitude = self.item.placemark.location.coordinate.latitude;
newPOI.longitude = self.item.placemark.location.coordinate.longitude;

I fixed it by changing my PointOfInterest : NSManagedObject subclass:

@property (nonatomic) double latitude;
@property (nonatomic) double longitude;

Is this the best way to make the compiler happy or is there a better way?


Solution

  • I would suggest you change the properties of your PointOfInterest subclass back to NSNumber, and then change your assignment of latitude and longitude as follows:

    newPOI.latitude = [NSNumber numberWithDouble:self.item.placemark.location.coordinate.latitude];
    newPOI.longitude = [NSNumber numberWithDouble:self.item.placemark.location.coordinate.longitude];
    

    Then when you want to use the latitude:

    self.item.placemark.location.coordinate.latitude = [newPOI.latitude doubleValue];
    

    etc.