Reputation: 156
Update:Michael got it right. Here is my solution:
- (void) connectNextCarOnMainThread:(id)annotation{
[self performSelectorOnMainThread:@selector(connectNextCar:) withObject:annotation waitUntilDone:YES];
}
- (void) connectNextCar:(id)annotation{
Pin *pin = (Pin *)annotation;
MKMapRect zoomRect = MKMapRectNull;
MKMapPoint annotationPoint = MKMapPointForCoordinate(pin.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 3, 3);
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect;
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
[mapView setVisibleMapRect:zoomRect animated:YES];
[mapView selectAnnotation:pin animated:YES];
NSInteger currentIndex=[self.annotations indexOfObject:annotation];
if(currentIndex < [self.annotations count]){
[self performSelector:@selector(connectNextCarOnMainThread:) withObject:[self.annotations objectAtIndex:currentIndex+1] afterDelay:5];
}
}
I want to achieve a simple feature: center and select one of my annotations every X seconds. But I'm getting some strange behavior in my annotation callouts.
Here is my code:
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
if(self.movedToFitPins){
for(id <MKAnnotation> pin in self.annotations)
[self.mapView addAnnotation:pin];
self.movedToFitPins = NO;
[self performSelectorInBackground:@selector(fakeCarConnections) withObject:nil];
}
}
- (void) fakeCarConnections {
for (Pin *annotation in self.annotations)
{
[NSThread sleepForTimeInterval : 10.0];
MKMapRect zoomRect = MKMapRectNull;
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 3, 3);
if (MKMapRectIsNull(zoomRect)) {
zoomRect = pointRect;
} else {
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
[mapView setVisibleMapRect:zoomRect animated:YES];
[mapView selectAnnotation:annotation animated:YES];
}
}
So, what is happening is that I do focus on the Annotation, the callout bubble does open but with no text inside. If i click in the annotation, the callout opens up correctly with the text.
Here is the catch: if I comment the sleepForTimeInterval line, the code works fine, but I only see the last annotation since it passes trough all the others.
Upvotes: 2
Views: 270
Reputation: 1462
All UI modifications/messages should occur on the main thread. I'd suggest that you modify your looping code so that instead of a sleep it uses performSelectorOnMainThread
after a time interval (and each subsequent call calls the next one). That way you won't block the main thread and will still get the desired effect.
Upvotes: 1