Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save MKMapRect in a plist

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.

like image 936
Robin Avatar asked Aug 03 '11 08:08

Robin


3 Answers

Use MKStringFromMapRect to turn it into a string.

like image 189
Nathan Day Avatar answered Oct 30 '22 17:10

Nathan Day


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;
}
like image 33
andreamazz Avatar answered Oct 30 '22 17:10

andreamazz


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
like image 2
malhal Avatar answered Oct 30 '22 17:10

malhal