NSMutableDictionary内存问题

时间:2010-12-10 10:35:03

标签: objective-c cocoa memory-leaks nsmutabledictionary

我正在制作iPhone应用程序,在地图上绘制叠加层。 我想在NSMutableDictionary中保存包含叠加层的数组,但只保存了我保存的最后一个条目:

    // Get "Kurwege" from CoreData
 NSError * error;
 if(![[self fetchedResultsController] performFetch:&error]) {
  NSLog(@"Unresolved error %@, %@", error, [error userInfo]); // TODO
 }

 if(self.overlaysDictionary == nil) {
  self.overlaysDictionary = [[NSMutableDictionary alloc] initWithCapacity:[fetchedResultsController.fetchedObjects count]];
 }

 NSString *path;
    for (Kurweg *kurweg in fetchedResultsController.fetchedObjects) {
  // Locate the path to the .kml file in the application's bundle
  // and parse it with the KMLParser.
  path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@", [[kurweg valueForKey:@"kmlfile"] description]] ofType:@"kml"];
  kml = [[KMLParser parseKMLAtPath:path] retain]; // PROBLEM: Executing this the second time seems to override my data stored in the dictionary

  // Save overlays in dictionary
  [self.overlaysDictionary setObject:[kml overlays] forKey:[NSString stringWithFormat:@"%@", [[kurweg valueForKey:@"kmlfile"] description]]];
  }

 // Draw overlays
 NSArray *keys = [overlaysDictionary allKeys];
 for (NSString *key in keys) {
  // Add all of the MKOverlay objects parsed from the KML file to the map.
  [map addOverlays:[overlaysDictionary objectForKey:key]];
 }

显然这是一个内存问题,但不幸的是我不知道如何保留存储在字典中的数据。

这是KML解析器中代码的摘录,取自Apple示例:

- (NSArray *)overlays {
NSMutableArray *overlays = [[NSMutableArray alloc] init];
for (KMLPlacemark *placemark in _placemarks) {
    id <MKOverlay> overlay = [placemark overlay];
    if (overlay)
        [overlays addObject:overlay];
}
return [overlays autorelease];

}

提前谢谢!

1 个答案:

答案 0 :(得分:0)

我的猜测是[[kurweg valueForKey:@"kmlfile"] description]]总是返回相同的值,所以你的字典中只有一个值。