Created
March 16, 2016 23:17
-
-
Save cliss/5716c3efb807ef078da1 to your computer and use it in GitHub Desktop.
Doing bad things with delegation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import CoreLocation | |
import XCPlayground | |
XCPlayground.XCPlaygroundPage.currentPage.needsIndefiniteExecution = true | |
class LocationDelegate: NSObject, CLLocationManagerDelegate { | |
override var description: String { | |
get { | |
return "LocationDelegate" | |
} | |
} | |
} | |
extension CLLocationManager { | |
var myDelegate: LocationDelegate { | |
get { | |
guard self.delegate == nil else { | |
fatalError("You're shit outta luck.") | |
} | |
self.delegate = LocationDelegate() | |
// 👇 Calling this fails because self.delegate is nil. | |
return self.delegate as! LocationDelegate | |
} | |
} | |
} | |
var locationManager = CLLocationManager() | |
print(locationManager.myDelegate.description) |
delegate
on CLLocationManager is unowned(unsafe)
.
I'd advise against creating an extension on CLLocationManager
and instead create a wrapper around it:
class LocationManager: NSObject, CLLocationManagerDelegate {
lazy var locationManager: CLLocationManager = {
let l = CLLocationManager()
l.delegate = self
return l
}()
}
let locationManager = LocationManager()
print(locationManager.locationManager.delegate)
Maybe I'm missing something but why do any of this? What's wrong with:
let locationDelegate = LocationDelegate()
let locationManager = CLLocationManager()
locationManager.delegate = locationDelegate
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Guess:
CLLocationManager.delegate
isweak
(is it?) so it's immediately deallocated after you call the initializer