[swift-users] Lifetime of objects in `class` methods

Nate Birkholz nbirkholz at gmail.com
Mon Jul 24 14:12:55 CDT 2017


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170724/aa3cb921/attachment.html>


More information about the swift-users mailing list