TAGS :Viewed: 13 - Published at: a few seconds ago

[ Annotations and Table Views ]

I am trying populate my table view using my array of annotations but XCode seems to give me a breakpoint any time I add this code.

if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

NSMutableArray *annotations = [[NSMutableArray alloc] init];

if(indexPath.section == 0)
{
    for(Location *annotation in [(MKMapView *)self annotations])
    {
        if(![annotation isKindOfClass:[MKUserLocation class]])
        {
    }
    }
    cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title];
}
return cell;

My annotations:

CLLocationCoordinate2D thecoordinate59;

thecoordinate59.latitude = 51.520504;
thecoordinate59.longitude = -0.106725; 
Location *ann1 = [[Location alloc] init];
ann1.title =@"Antwerp";
ann1.coordinate = thecoordinate1;

NSMutableArray *annotations = [NSMutableArray arraywithObjects: ann.. ann59, nil];

[map addAnnotations:annotations];

Answer 1


In cellForRowAtIndexPath, you are declaring a new, local variable named annotations which has nothing to do with the annotations array you are creating in viewDidLoad (I assume that's where you're adding the annotations).

Then in cellForRowAtIndexPath, this line:

for(Location *annotation in [(MKMapView *)self annotations])

fails because there is no annotations property in self. In viewDidLoad, you declared a local variable named annotations but it is not visible or accessible outside that method.

The other issue with the above line is that you're casting self as an MKMapView *. Most likely self is a UIViewController. It contains a map view but is not itself one.


You need to first declare your annotations array at the detail view's class level so it's available across all methods. In the detail view .h file:

@property (nonatomic, retain) NSMutableArray *annotations;

By the way, I'd name it something different so it's not confused with the map view's own annotations property.

In the .m, synthesize it:

@synthesize annotations;

In viewDidLoad, create it like this:

self.annotations = [NSMutableArray arraywithObjects...
[map addAnnotations:self.annotations];

In the numberOfRowsInSection method, return the array's count:

return self.annotations.count;

Then in cellForRowAtIndexPath:

if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

if(indexPath.section == 0)
{
    cell.textLabel.text = [[self.annotations objectAtIndex:indexPath.row] title];
}
return cell;

Answer 2


You are reporting a crash (i assume) on that line

the problem that I see is crash reason would be

cell.textLabel.text = [[annotations objectAtIndex:indexPath.row] title];

annotations array is just initialized locally few statements above which does not hold any values..??