Skip to content

Instantly share code, notes, and snippets.

@cliss
Created March 16, 2016 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cliss/5716c3efb807ef078da1 to your computer and use it in GitHub Desktop.
Save cliss/5716c3efb807ef078da1 to your computer and use it in GitHub Desktop.
Doing bad things with delegation
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)
@Peterbing
Copy link

Guess: CLLocationManager.delegate is weak (is it?) so it's immediately deallocated after you call the initializer

@OscarSwanros
Copy link

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)

@cbguder
Copy link

cbguder commented Mar 17, 2016

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