How to save MKMapRect in a plist
I am creating a MKMapView application and开发者_如何学JAVA 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
You could probably copy the MKMapRect data in a CGRect, then store the CGRect as a string with NSStringFromgCGRect() and CGRectFromString()
精彩评论