apple / swift-migration-guide

Apache License 2.0
284 stars 20 forks source link

"Never extend the life-time of self from within deinit" #137

Open Gargo opened 3 weeks ago

Gargo commented 3 weeks ago

https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/commonproblems/

Never extend the life-time of self from within deinit. Doing so will crash at runtime.

I had a code with an object which is created in a background thread (and is destroyed in the same thread because it is default iOS behavior). In the same time the app expects this object being deinited in the main thread.

I didn't have an influence on the thread in which the object inited so I had to delay its deiniting until the main thread. In the same time according to your comments I can't do that. How to resolve it in other way then?

mattmassicotte commented 3 weeks ago

The Objective-C and Swift runtimes have never provided any guarantees about the scheduling of deinit. Some specific objects in some frameworks do, but nothing in the general case.

This might be something worth asking on forums.swift.org. Unless you think the guide is missing some more specific details?

ktoso commented 1 day ago

The isolated deinit proposal will be of help here: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0371-isolated-synchronous-deinit.md

But otherwise it might be good to call out the Task { self.stuff } being a bad idea™ since it's so tempting to use it. Copying some resource to then close into the task is more safe and sometimes okey though.