以线程安全的方式删除MKAnnotations

时间:2014-08-28 07:00:26

标签: ios objective-c mapkit mkannotation

我是Objective-C的新手,所以原谅我的无知:

我有一个在类WGMap : MKMapView中声明的方法,如下所示:

- (void)cleanupMap { NSLog(@"Cleaning up the map!"); NSSet* visible = [self annotationsInMapRect:[self visibleMapRect]]; NSArray* all = [self annotations]; NSMutableArray* discard = [NSMutableArray array]; for (id<MKAnnotation> cur in all) { if (![visible containsObject:cur]) [discard addObject:cur]; } [self removeAnnotations:discard]; } 目的是清理当前不在屏幕上的MKAnnotations以节省内存。我使用GCD调度计时器定期调用此方法。

我有另一种并行运行的方法,偶尔会将MKAnnotations添加到MKMapView中。我注意到我偶尔会收到以下错误: **** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x17025ed20> was mutated while being enumerated.'

有时候,我会得到一个类似的数组超出范围的错误。

我该如何防止这种情况发生?我已经尝试制作我的类(来自MKMapView)NSArray* annotations属性atomic而不是默认的nonatomic,但它没有解决问题。

1 个答案:

答案 0 :(得分:0)

您正在获取异常,因为您正在迭代self.annotations并在该迭代中从中移除内容。

相关问题