我正在编写一个iOS应用程序来记录您的旅行路径,然后将其存储起来以便稍后可以检索它。绘制路径的大部分代码都基于示例代码Breadcrumb。如何将MKOverlay对象存储到文件以供稍后检索
现在我正在添加功能以保存绘制的叠加层。什么是最好的方式来做到这一点?我可以使用CoreData
,但我不希望对绘制的叠加层做很多工作,而不是稍后再检索它。我目前已经尝试了一个简单的NSArray
。我将CrumbPath对象转换为NSData
并将其存储在数组中。稍后我会检索它并将其转换回CrumbPath。但是,我似乎做错了什么。
@interface CrumbPath : NSObject <MKOverlay>
{
MKMapPoint *points;
NSUInteger pointCount;
NSUInteger pointSpace;
MKMapRect boundingMapRect;
pthread_rwlock_t rwLock;
}
- (id)initWithCenterCoordinate:(CLLocationCoordinate2D)coord;
- (MKMapRect)addCoordinate:(CLLocationCoordinate2D)coord;
@property (readonly) MKMapPoint *points;
@property (readonly) NSUInteger pointCount;
@end
我节省CrumbPath对象 “面包屑” 是这样的:
NSData *pointData = [NSData dataWithBytes:crumbs.points length:crumbs.pointCount * sizeof(MKMapPoint)];
[patternArray addObject:pointData];
[timeArray addObject:date];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Create the full file path by appending the desired file name
NSString *patternFile = [documentsDirectory stringByAppendingPathComponent:@"patterns.dat"];
NSString *timeFile = [documentsDirectory stringByAppendingPathComponent:@"times.dat"];
//Save the array
[patternArray writeToFile:patternFile atomically:YES];
[timeArray writeToFile:timeFile atomically:YES];
后来这样获取在表中显示:
NSData *pointData = [appDelegate.patternArray objectAtIndex:indexPath.row];
MKMapPoint *points = malloc(pointData.length);
(void)memcpy([pointData bytes], points, sizeof(pointData));
并再次构建路径:
crumbs = [[CrumbPath alloc] initWithCenterCoordinate:MKCoordinateForMapPoint(points[0])];
for (int i = 1; i <= pointCount; i++) {
[crumbs addCoordinate:MKCoordinateForMapPoint(points[i])];
}
[map addOverlay:crumbs];
但是,我得到一个错误:'NSInvalidArgumentException', reason: '-[NSConcreteData isEqualToString:]: unrecognized selector sent to instance
与您的例外无关,您向我们显示您对'malloc'的调用,但不显示相应的'免费'调用。我假设你有这个地方,但确保你自己清理。或者你可以避免调用'malloc'和'memcpy'(就像我下面的代码示例),你不必担心它。 – Rob 2013-03-01 04:09:35