iOS有IEnumerator Coroutines(C#)就像异步运行任务一样吗?

时间:2014-06-25 20:25:58

标签: ios objective-c xcode mkmapview

我想知道是否可以使用像协程这样的东西来延迟iOS中的某些操作但是没有冻结应用程序的地狱?更具体地说,我想让MKMapView更新位置,但不要在用户交互之后再告诉他等一下。因为我发现的每个答案都有点像是如果它更新它将视图集中在用户的实际位置上,它的工作完美无瑕,但是一旦我想离开它的位置就会把我带回那里。所以我想做一些好的事情,将mapview集中到当前位置,但是如果有一个交互等待几秒钟然后你应该移回视图。可能吗?

- (void)mapView:(MKMapView *)aMapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {
/*MKCoordinateRegion region;
MKCoordinateSpan span;
span.latitudeDelta = 0.005;
span.longitudeDelta = 0.005;
CLLocationCoordinate2D location;
location.latitude = aUserLocation.coordinate.latitude;
location.longitude = aUserLocation.coordinate.longitude;
region.span = span;
region.center = location;
[aMapView setRegion:region animated:YES];*/
[self.mapView setCenterCoordinate:aUserLocation.coordinate animated:YES];
NSLog(@"Before sleep");
//[NSThread sleepForTimeInterval:7];
double delayInSeconds = 5.0;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
    // do your work here
});
NSLog(@"Fater sleep");
}

1 个答案:

答案 0 :(得分:0)

如果我理解了这个问题,答案就是使用GCD dispatch_after

double delayInSeconds = 5.0;
dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
    // do your work here
});

此延迟调用可以放在用户交互的处理程序中。

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)aUserLocation {

    __weak typeof(self) weakSelf = self;
    double delayInSeconds = 5.0;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
        // the mapView will center itself 5 seconds after didUpdateUserLocation is called
        [weakSelf.mapView setCenterCoordinate:aUserLocation.coordinate animated:YES];
    });
}