Jules
Jules

Reputation: 660

Serialize mkcoordinateregion to store in core data?

What is the best way to store an MKCoordinateRegion using core data? I assume there is a way to convert this to binary data somehow??

Many thanks

Jules

Upvotes: 1

Views: 1237

Answers (2)

Jano
Jano

Reputation: 63667

MKCoordinateRegion region;

// region to NSData
NSData *data = [NSData dataWithBytes:&region length:sizeof(region)];    

// NSData to region
[data getBytes:&region length:sizeof(region)];

This works in any iOS version, for any struct, with Core Data, NSUserDefaults, or NSKeyedArchiver. It is portable between any system running on the same architecture (all iOS versions run on little-endian 32 bit).
If you use this for archiving, an alternative is subclassing NSCoder or create a NSCoder category.

Upvotes: 7

Michael Nachbaur
Michael Nachbaur

Reputation: 382

My suggestion is to simply store the MKCoordinateRegion's struct values (latitude, longitude, latitudeDelta, and longitudeDelta) as separate properties, and then on your model class provide a custom accessor that assembles these into a MKCoordinateRegion object.

For example:

// Snip...boilerplate CoreData code goes here...
@dynamic latitude;
@dynamic longitude;
@dynamic latitudeDelta;
@dynamic longitudeDelta;

- (MKCoordinateRegion)region {
    CLLocationCoordinate2D center = {
        [self.latitude floatValue],
        [self.longitude floatValue]
    };
    MKCoordinateSpan span = {
        [self.latitudeDelta floatValue],
        [self.longitudeDelta floatValue]
    };

    return MKCoordinateRegionMake(center, span);
}

If you want to be extra clever, you can create a custom read-only property that exposes the internal data as above.

Upvotes: 1

Related Questions