2014-08-28 17 views
0

我是新來的Objective-C,所以請原諒我的無知:刪除MKAnnotations

我已經宣佈了一種方法,一類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,但它沒有解決問題。

+0

如果viewForAnnotation方法已實現並正確使用視圖出隊/重用機制,則不需要自己執行此操作。你怎麼知道你有「高內存使用率」問題? – Anna 2014-08-28 10:49:58

回答

0

你會得到例外,因爲你在迭代中迭代self.annotations並從中刪除它。

+0

雖然我不會在該迭代中刪除它;請注意,我選擇要刪除的MKAnnotations並將它們添加到單獨的NSMutableArray;在迭代之後,我實際上並沒有刪除註釋。問題是,在我的應用程序的其他地方,註釋正被添加到地圖中。我正在尋找一種方法來使此線程安全,以防止此問題。 – gautam 2014-08-28 22:23:26