[swift-users] Lifetime of objects in `class` methods
Hooman Mehr
hooman at mac.com
Mon Jul 24 15:55:38 CDT 2017
In the class method case, the scope of your `manager` object is local the the class method and it is deallocated immediately as function returns (before the closure gets a chance to be called).
> On Jul 24, 2017, at 12:22 PM, Nate Birkholz via swift-users <swift-users at swift.org> wrote:
>
> If I use these two classes:
>
> class MotionManager {
>
> class func doTheThing(completionHandler: @escaping (CMDeviceMotion?)->() ) {
> print("in")
> let manager = CMMotionManager()
> manager.deviceMotionUpdateInterval = 0.01
>
> manager.startDeviceMotionUpdates(to: .main) { (motion, error) in
> print("out")
> completionHandler(motion)
> }
> }
> }
>
> class OtherManager {
> let manager: CMMotionManager
>
> init() {
> manager = CMMotionManager()
> manager.deviceMotionUpdateInterval = 0.01
> }
>
> func doTheThing(completionHandler: @escaping (CMDeviceMotion?)->() ) {
> print("in 2")
> manager.startDeviceMotionUpdates(to: .main) { (motion , error) in
> completionHandler(motion)
> print("out 2")
> self.manager.stopDeviceMotionUpdates()
> }
> }
> }
>
> let other = OtherManager()
>
> other.doTheThing { (motion) in
> print(motion)
> }
>
> MotionManager.doTheThing { (motion) in
> print(motion)
> }
>
> The class method on MotionManager prints "in" but never prints "out". The instance method version on. OtherManager works just fine, printing "in 2" and "out 2". Clearly the CMMotionManager doesn't survive long enough to finish its call, but I would have thought it would.
>
> Is this a bug? Or am I just misunderstanding how the class method should work?
>
> --
> Nate Birkholz
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170724/e213316f/attachment.html>
More information about the swift-users
mailing list