ios - 如何避免对 2 个不同的类使用具有相同方法的两个扩展
问题描述
我想知道处理这种情况的最佳方法是什么。我有两个不同的视图控制器,它们都将使用来自 CLlocationManagerDelegate 的相同 didUpdateLocations 方法。我对它们都使用了扩展,并使它们符合 CLManagerDelegate。我想知道是否有另一种方法可以获得相同的结果。感谢所有的解释和回复。
第一个视图控制器
extension FirstViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
}
}
}
第二个视图控制器
extension SecondViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
}
}
}
我正在考虑下面的代码,但我不知道它是否比以前更好,并且对第二个视图控制器做同样的事情。
protocol localisation {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
}
extension FirstViewController: localisation, CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
}
}
解决方案
我认为您的问题中有错字,因为代码SecondViewController
用作FirstViewController
名称。
如果我理解正确,您有两个视图控制器符合CLLocationManagerDelegate
相同的代码,两者都重复。如果这就是您要解决的问题,我的建议是创建一个BaseViewController
符合的CLLocationManagerDelegate
,然后让您ViewControllers
继承自BaseViewController
.
class BaseViewController: UIViewController {
//Common code here
}
extension BaseViewController: CLLocationManagerDelegate{
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations[locations.count - 1]
if location.horizontalAccuracy > 0 {
locationManager.stopUpdatingLocation()
print("\(location.coordinate.longitude), \(location.coordinate.latitude)")
}
}
}
class FirstViewController: BaseViewController {
//Your code here
}
class SecondViewController: BaseViewController {
//Your code here
}
推荐阅读
- sql-server - 使用默认(已提交读)隔离模式时如何确保原子规则?
- javascript - Github Pages 在尝试抓取 paper.js 资源时返回 404 错误
- .net - UseStatusCodePagesWithReExecute() 在 .NET Core 3.1 上不起作用
- javascript - 从Angular中的CSV文件读取后如何在UI上填充数据?
- python - 在哪里可以找到照片
- java - 如何检查 SD 卡是格式化为手机存储还是便携式存储?
- java - 在 vertx.executeBlocking 代码中使用 mybatis 代码有什么大问题吗?
- javascript - 隔离子串
- apache-spark - spark RDD 中的分区数
- r - 无法将 csv 分成单独的列