Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store CLLocation using Core Data (iPhone)?

I'm trying to save a location and retrieve the location on a map afterward using Core Location, MapKit and Core Data frameworks.

What I've done is I just made entity named POI and added properties such as latitude (double type), longitude (double type) with few others.

Simply put, my app saves POI with two NSNumbers. (lat and long) but I feel like there must be a smarter way to store CLLocation than that.

cheers.

like image 483
bicbac Avatar asked Sep 26 '10 08:09

bicbac


2 Answers

What you're doing is fine. You should save the latitude and longitude as doubles in Core Data. When you need to get the information again, get the doubles back from Core Data and construct a CLLocationCoordinate2D struct with a function like CLLocationCoordinate2DMake. There's no built in way to store a location, so storing the latitude and longitude components is fine.

If you're not doing any math operations on the latitude or longitude (finding bounding boxes etc) you could store them as strings. Floats and doubles can change their values slightly, making comparison operations fail.

like image 70
nevan king Avatar answered Sep 28 '22 04:09

nevan king


CLLocation implements the NSCoding protocol so you can store them in Core Data as transformable attributes. You can use the default NSKeyedUnarchiveFromData value transformer.

You would just pass the CCLocation object to the managed object attribute and it would serialize it to data and store it as a blob in the SQL store. When you need the location object back it would automatically reverse the process and return to you a fully populated CCLocation object.

That might be the easiest way to get what you want.

like image 22
TechZen Avatar answered Sep 28 '22 05:09

TechZen