更新:迈克尔做对了。这是我的解决方案:
- (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];
}
}
我想实现一个简单的功能:居中并每隔X秒选择一个注释。但是我的注释标注中出现了一些奇怪的行为。
这是我的代码:
- (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];
}
}
所以,正在发生的事情是我专注于注释,标注气泡确实打开但内部没有文字。如果我单击注释,标注将正确打开文本 这是一个问题:如果我评论sleepForTimeInterval行,代码工作正常,但我只看到最后一个注释,因为它通过了所有其他注释。
答案 0 :(得分:1)
所有UI修改/消息都应在主线程上发生。我建议您修改循环代码,使其在一段时间间隔后使用performSelectorOnMainThread
而不是睡眠(并且每个后续调用都会调用下一个)。这样你就不会阻塞主线程,仍然可以获得所需的效果。