【发布时间】:2013-03-01 02:30:47
【问题描述】:
我正在编写一个 iOS 应用程序来记录您的旅行路径,然后将其存储起来以便以后检索。大部分绘制路径的代码都是基于示例代码Breadcrumb。
现在我正在添加功能来保存绘制的叠加层。最好的方法是什么?我可以使用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 对象“crumbs”:
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的调用,而不是对应的free调用。我假设您在某个地方有那个,但请确保您自己清理干净。或者您可以避免调用malloc和memcpy(如下面的代码示例),您不必担心。
标签: ios nsarray nsdata mkoverlay writetofile