class Example {}
unowned let first = Example()
This produces the error:
Attempted to read an unowned reference but object 0x60c000005f20 was already deallocated
I'm trying to dig deep into understanding exactly what keyword unowned
does.
class Example {}
unowned let first = Example()
This produces the error:
Attempted to read an unowned reference but object 0x60c000005f20 was already deallocated
I'm trying to dig deep into understanding exactly what keyword unowned
does.
Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime.
In your example up there, as soon as "Example()
" is called, your new
property is deallocated (new
is a terrible name for even a property, even if only for a demo :-).
So what could work here would be:
class Example {}
let oneExample = Example() // properties are strong by default
unowned let theSameExample = oneExample
From The Swift Programming Language:
You create a new instance of
Example
, and assign it to your unowned constantfirst
. There is nothing holding a strong reference to yourExample
instance so it is immediately deallocated. Your unowned constantfirst
is now holding a reference to this deallocated object so you get the error that you are attempting to read a deallocated object.The
unowned
keyword is used to create a weak reference to an object where you can guarantee that the lifetime of the referenced object is the same as the referring object. This enables you to prevent reference loops while avoiding the need to unwrap an optional (as would be the case withweak
).