Reputation: 78
everyone. I have two possibilities to code:
I have a mapView, that needs to have some variables. I wonder what is the best way to do it ?
First:
class UGOMapView: MKMapView, MKMapViewDelegate, CLLocationManagerDelegate {
let regionRadius: CLLocationDistance = 1000
var usrLocation: CLLocationManager!
var annotationView: MKAnnotationView!
func initUserLocation() {
if (CLLocationManager.locationServicesEnabled()) {
usrLocation = CLLocationManager()
usrLocation.delegate = self
usrLocation.requestAlwaysAuthorization()
usrLocation.requestLocation()
}
}
}
Then in my storyboard:
and in my controller : @IBOutlet weak var mapView: UGOMapView!
Or :
class MainViewController: UIViewController, MKMapViewDelegate, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
let regionRadius: CLLocationDistance = 1000
var usrLocation: CLLocationManager!
var annotationView: MKAnnotationView!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled()) {
usrLocation = CLLocationManager()
usrLocation.delegate = self
usrLocation.requestAlwaysAuthorization()
usrLocation.requestLocation()
}
}
Then in my storyboard:
(I have more than one function in my mapView. I don't know if the functions there is matter for one way or another?)
Upvotes: 1
Views: 36
Reputation: 326
The main difference of between First approach and Second approach is Code Reuseablilty.
First approach is always better idea because whenever you need to modify or change anything with that class you can directly redirect to that class.
Where in second approach it become unmanageable when you need to add some changes which makes you confusing.
Read this throughly : https://www.objc.io/issues/13-architecture/subclassing/
You will get better idea when to subclass and when not.
Upvotes: 1
Reputation: 2693
Your first approach is good. It is because, it gives you code separation and single point of modification. If you create separate class for your map view, and suppose any issue comes related to map, you will be pretty sure that the lines of code causing issue will be in this class. Also if you want to handle map related actions , you can handle them here. One more benefit is that you can use same class for multiple map views. In case of view controller, you can't use the same code for other map view.
Upvotes: 1