views:

131

answers:

1

In a tableview cellForRowAtIndexPath, I do the following:

MapViewController *mapView = [[MapViewController alloc] initWithCoordinates:city.Latitude longitude:city.Longitude];
[cell addSubview:mapView.view];
//[mapView release]; -- will crash here

Calling the last line gives this memory error EXC__BAD _ACCESS”. How do I release the above memory I've alloc'ed wthout crashing?

From above, cell is a UITableViewCell.

MapViewController is a UIViewController that implements MKReverseGeocoderDelegate and MKMapViewDelegate. In MapViewController's init, it allocs an MKMapView. In the controller's viewDidLoad, it adds the mapview to the UIViewController's view:

[self.view addSubview:mapView];
+1  A: 

I think you are going to need to rearchitect this. Without seeing all of the code I can't be 100% sure, but it seems that you are getting rid of MapViewController before you are done with it. Yes, you no longer are explicitly using it, but the view you pulled out of it is almost certainly not holding a retain against its view controller (generally controllers retain views, not the other way around). So when you release it it deallocs and now the subview you just added is referencing a deallocated object. You can test this by turning on NSZombies.

You need to deallocated MapViewController after the view it is attached to is removed from the cell. You should probably subclass UITableViewCell and make the MapViewController an ivar of that class. Then you can release it during the cells dealloc routine.

Louis Gerbarg