Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_swift_abortRetainUnowned when capturing @objc class as unowned

I am experiencing this strange crashing when capturing an instance of a @objc class (written in swift, but annotated with @objc and subclass of NSObject). It happens when the closure is being assigned and not when called, so the problem is not that the captured value would get deallocated and then the closure called. It happens randomly, sometimes it crashes sooner, sometimes later. I was experiencing this bug in earlier versions of Swift (I think it was Swift 1.2), but now I'm using 2.1 and getting this crash too.

It works well when I change [unowned x] to [weak x] and then access it by force unwrapping x!.doSomething() which leads me to believe it is a bug in Swift, rather than in my code. However before opening a ticket at bugs.swift.org, I wanted to get more eyes on this to make sure I'm not missing anything.

It was also mentioned here:
http://www.codeproject.com/Articles/791304/Resolving-strong-references-between-Swift-and-Obje
here:
https://www.reddit.com/r/swift/comments/3vhwmj/unowned_bug_in_closure_causes_attempted_to_retain/
and here:
https://forums.developer.apple.com/thread/9873

But other than changing the capture to weak and force unwrapping it later, there is no solution.

like image 207
Tadeas Kriz Avatar asked Dec 23 '15 12:12

Tadeas Kriz


1 Answers

Usually I prefer to use this code instead of unowned when I've to do with some included objc classes:

[weak self] in
guard let strongSelf = self else { return }
// use strongSelf below
like image 121
Alessandro Ornano Avatar answered Oct 31 '22 20:10

Alessandro Ornano