只是关于代表如何工作的问题。
编辑:
因为我可能让你感到困惑,这是我的应用程序的结构。
具有一些委托功能的LocationManager 。
此类定义了一些委托方法,例如:
@protocol LocationManagerDelegate <NSObject>
@optional
- (void)locationManager:(LocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance;
@end
我的MainViewController实例化了 LocationManager 并实现了委托的功能。
[LocationManager sharedLocationManager].delegate = self;
所以,在 LocationManager 里面有这个函数:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
在其中我调用了一个自定义函数 f1,以及一个像这样的委托函数:
[self.delegate locationManager:self distanceUpdated:self.totalDistance];
在我的 MainViewController 中实现的委托函数中的代码是这样的:
- (void)locationManager:(LocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance {
self.totalDistanceCovered.text= [NSString stringWithFormat:@"%.2f %@", distance, NSLocalizedString(@"meters", @"")];
}
所以我的问题是:
哪个更有效并且不会阻止我的应用程序?
这个解决方案:
在位置管理器中
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
...
[self.delegate locationManager:self distanceUpdated:self.totalDistance];
...
f1();
}
在主视图控制器中
- (void)locationManager:(PSLocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance {
self.totalDistanceCovered.text= [NSString stringWithFormat:@"%.2f %@", distance, NSLocalizedString(@"meters", @"")];
}
或者
在位置管理器中
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
...
[self.delegate locationManager:self distanceUpdated:self.totalDistance];
...
}
在主视图控制器中
- (void)locationManager:(PSLocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance {
self.totalDistanceCovered.text= [NSString stringWithFormat:@"%.2f %@", distance, NSLocalizedString(@"meters", @"")];
f1();
}
还是它们完全一样?
我的意思是它将作为委托方法实现,实际代码将在我的 mainViewController 中。(将逻辑移到我的 didUpdate 之外 - 并将它放在我的 mainViewController 中)更好吗?因为现在在我的 didUpdate 中我正在执行一些额外的事情。还是一样?
调用委托方法时,调用它的位置是停止并等待完成,还是继续并独立于委托方法运行?(例如,我认为它可能被分配给不同的线程,因此它不会停止 - 因此我的更新不会等待我的自定义函数完成,但它会继续获取位置的更新)。
你能帮助我吗?