只是有关代表如何工作的一个问题。
编辑:
因为我可能让您感到困惑,所以这是我的应用程序的结构。
具有某些委托功能的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", @"")];
}
所以我的问题是:
哪个效率更高,并且不会阻止我的应用程序?
此解决方案:
在LocationManager中
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
...
[self.delegate locationManager:self distanceUpdated:self.totalDistance];
...
f1();
}
在mainViewController中
- (void)locationManager:(PSLocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance {
self.totalDistanceCovered.text= [NSString stringWithFormat:@"%.2f %@", distance, NSLocalizedString(@"meters", @"")];
}
要么
在LocationManager中
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
...
[self.delegate locationManager:self distanceUpdated:self.totalDistance];
...
}
在mainViewController中
- (void)locationManager:(PSLocationManager *)locationManager distanceUpdated:(CLLocationDistance)distance {
self.totalDistanceCovered.text= [NSString stringWithFormat:@"%.2f %@", distance, NSLocalizedString(@"meters", @"")];
f1();
}
还是它们完全相同?
我的意思是说它将被实现为委托方法,而实际的代码将在我的mainViewController中。 (将逻辑移到didUpdate之外-并在mainViewController中)是否更好?因为现在在我的didUpdate中,我正在执行一些额外的操作。还是一样?
调用委托方法时,是从哪里调用停顿并等待完成的地方,还是继续并独立于委托方法运行的地方?
(例如,我有可能将其分配给其他线程,因此它不会停滞-因此,我所做的更新不会等待自定义函数完成,而是会继续获取位置更新)。
你能帮助我吗?
最佳答案
当您提供委托方法时,调用您的委托所需的正在运行的线程将被阻塞,直到您的方法返回为止(假设它们没有具体实现异步回调的调用)。
如果您的委托方法更新了一个与UI相关的项目,就像您看起来的那样,那么您会遇到问题,因为与UI相关的项目必须在主线程上进行处理。
避免性能问题的方法是让您的委托成为“模型”对象-而不是调用UI工具包的对象。您应该有一个单独的NSNotification侦听器,例如updateUIFromModel,每当您的模型更新到UI需要更新的程度时,就会发出信号。应该从主线程调度此侦听器,因此它仅更新主线程上与UI相关的项。当与您的位置相关的代表被呼叫时,您可以发出通知,让您的听众接听并更新UI。
关于ios - 在objC的委托(delegate)方法内执行自定义功能的有效方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18794697/