I am creating a MKMapView application and in need to save a couple MKMapRect type variables in a plist so as to refer them when need.
I know that MKMapRect has MKMapPoint origin
and MKMapSize size
. And they each have 2 double values that can be saved as nsnumber
but saving all of them seems to be a lot of work and top of that i have to read the values back and convert them into a MKMapRect variable.
So my question is that, is there any easy way to store a MKMapRect and retrive it back from a plist.
Thanks,
Robin.
Use MKStringFromMapRect to turn it into a string.
There:
- (NSString *)save:(MKMapRect)rect
{
return MKStringFromMapRect(rect);
}
- (MKMapRect)load:(NSString *)str
{
MKMapRect mapRect;
CGRect rect = CGRectFromString(str);
mapRect.origin.x = rect.origin.x;
mapRect.origin.y = rect.origin.y;
mapRect.size.width = rect.size.width;
mapRect.size.height = rect.size.height;
return mapRect;
}
I made a category to save the map rect to the user defaults:
NSUserDefaults+MKMapRect.h
@interface NSUserDefaults (MKMapRect)
//stores a map rect in user defaults
-(void)setMapRect:(MKMapRect)mapRect forKey:(NSString*)key;
//retrieves the stored map rect or returns the world rect if one wasn't previously set.
-(MKMapRect)mapRectForKey:(NSString*)key;
@end
NSUserDefaults+MKMapRect.m
@implementation NSUserDefaults (MKMapRect)
-(void)setMapRect:(MKMapRect)mapRect forKey:(NSString*)key{
NSMutableDictionary *d = [NSMutableDictionary dictionary];
[d setObject:[NSNumber numberWithDouble:mapRect.origin.x] forKey:@"x"];
[d setObject:[NSNumber numberWithDouble:mapRect.origin.y] forKey:@"y"];
[d setObject:[NSNumber numberWithDouble:mapRect.size.width] forKey:@"width"];
[d setObject:[NSNumber numberWithDouble:mapRect.size.height] forKey:@"height"];
[self setObject:d forKey:key];
}
-(MKMapRect)mapRectForKey:(NSString*)key{
NSDictionary *d = [self dictionaryForKey:key];
if(!d){
return MKMapRectWorld;
}
return MKMapRectMake([[d objectForKey:@"x"] doubleValue],
[[d objectForKey:@"y"] doubleValue],
[[d objectForKey:@"width"] doubleValue],
[[d objectForKey:@"height"] doubleValue]);
}
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With