Are Unowned references set to 'nil' when deinitialized? - ios

I'm confused on this topic in swift where it is said that unowned references must always have a value and cannot be optional, also meaning they cannot be set to 'nil'....well I just saw a program on the Apple documents for swift that instance 'A' with an unowned reference to instance 'B' was deinitialized and deallocated right after instance 'B' was deinitialized/deallocated......when a var is deinitialzed/dealloc doesn't it mean they are set to 'nil'??? Instance B is an optional so sure it can hold 'nil' but why did instance 'A' get deinitialized when its supposed to always have a value????
PS: If this helps..... instance 'B' was an optional type with a strong reference to instance 'A'

The point of an unowned reference is to hold a weak reference to something that you are guaranteeing (based on your application logic) will not be deallocated prior to the object that has the unowned reference. You can read more in the documentation.
In a sense it is a similar thing to an implicitly unwrapped optional type (such as String!). You're telling the compiler that you won't ever access the value when it is nil, and if you do your program will crash.

An object is deinitialized when its strong reference count drops to 0, but it is not deallocated until its weak reference count also drops to zero.
"Deinitializing" an object means that its deinit function is executed if it has one, releasing any resource that it holds, and clearing any references that it may have (potentially deinitializing and deallocating more objects). "Deallocating" is when the memory is reclaimed by the runtime. A deinitialized object's reference counting header is still valid.
When you access a weak reference, the Swift runtime ensures that the object is still in an initialized state. If it isn't, the weak reference is set to nil and the deinitialized object's weak reference count is decremented.
Unowned references also count towards the weak reference count. When you access an unowned reference, the Swift runtime also ensures that the object is in an initialized state; but if it is not, instead of clearing the reference (it can't do that because it is not optional), it crashes your program.
This effectively makes an unowned reference behave like an implicitly-unwrapped optional, whereas a weak reference behaves like an optional.
The tradeoff for self-zeroing weak references and clean-crashing unowned references is that an object's backing memory cannot be reclaimed until all of its weak references have been tested or deinitialized, and until all of its unowned references have been deinitialized.
Source: Swift runtime code

It is meaningless to talk about what an unowned variable "holds" after the object it points to has been deallocated, because Swift guarantees that your app will crash if you ever try to access the variable after the object it points to has been deallocated:
Note also that Swift guarantees your app will crash if you try to
access an unowned reference after the instance it references is
deallocated. You will never encounter unexpected behavior in this
situation. Your app will always crash reliably, although you should,
of course, prevent it from doing so.

Related

Why Reference Counters All Start with +1?

As per swift/stdlib/public/SwiftShims/RefCount.h:
- The strong RC is stored as an extra count: when the physical field is 0 the logical value is 1.
- The unowned RC also has an extra +1 on behalf of the strong references
- The weak RC also has an extra +1 on behalf of the unowned references
I'm wondering why an object initialises with +1 to all counters, what's the point of making extras?
The unowned count is stored in the object's directly-allocated storage. When an unowned reference is destroyed, the runtime decrements the unowned count. If the decremented count is still above zero, the runtime knows that there is still at least one strong or unowned reference to the object, so the runtime knows it should not deallocate the object's storage. (The storage remains allocated until all strong and unowned references to the object are destroyed.) So, when the runtime destroys an unowned reference, it doesn't have to check the strong count to know whether to deallocate the storage. This saves time in the case where all unowned references are destroyed before the last strong reference is destroyed.
The weak count is stored in the object's “side table” entry, which isn't allocated until it's needed (which is usually when the first weak reference to the object is created). When a weak reference is destroyed, the runtime decrements the weak count. If the decremented count is still above zero, the runtime knows that there is still at least one strong or unowned or weak reference to the object, so the runtime knows it should not deallocate the side table entry for the object. (The side table entry remains allocated until all strong, unowned, and weak references to the object are destroyed.) So, when the runtime destroys a weak reference, it doesn't have to check the unowned count (or the strong count) to know whether to deallocate the side table entry. This saves time in the case where all weak references are destroyed before the last unowned (or strong) reference is destroyed.

Is it redundant in Swift to use weak and optional for the same variable?

I'm new in Swift and in the Apple docs I see:
Use a weak reference whenever it is valid for that reference to become >nil at some point during its lifetime.
Shouldn't I achieve that just by using "?" for optional types?
in other words:
Do the weak and ? overlap?
The compiler complains if I don't define a variable as optional when is weak, so I feel like I could just remove it and forget about it, but I feel I'm just misunderstanding it.
Thanks!
No, weak and optional are not the same, but there is some interplay between the two.
Optional just means that a variable can be nil, either by assigning nil yourself, or becoming nil through some other means.
The weak keyword has to do with memory management. When a variable is not weak (i.e. it is strong), it means that ARC holds a strong reference to the instance that is assigned. So even when there are no other references to it, the instance will stay alive in memory because the variable still "holds it".
When a a variable is weak, it does not hold a strong reference to it. That means that when there are no other strong references to it, the instance will be deallocated, and the variable will become nil automatically. This also explains why a weak variable must be optional.
The document that you linked to actually explains this quite clearly.
weak is related to memory management that ARC should remove that variable from memory or not. If your variable is weak then ARC would clear that memory to which it is pointing to as soon as all the strong references to that memory destroyed and when the memory is cleared then even the varaible is non-optional it will have nill because its memory is cleared.
But the optional has nothing to do with memory and it is directly related to the variable value that it can either contains the actual value or the nil.
Optional and non-optional properties differ in that optionals may be nil, while non-optional cannot.
weak and strong (property is strong by default without weak keyword) properties differ in that weak don't increase property's retain count, while strong do. If a weak property isn't strongly retained somewhere else, it will be deallocated. weak properties must also be optional.

Why can't I give an unowned constant an initial value?

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.
From The Swift Programming Language:
Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to.
You create a new instance of Example, and assign it to your unowned constant first. There is nothing holding a strong reference to your Example instance so it is immediately deallocated. Your unowned constant first 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 with weak).
Apple's documentation says:
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 (newis 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

Does ARC set its reference type instance properties to nil before deallocation?

This question occured to me while reading this.
My question is in reference to the image below:
Once john is set to nil, Person instance no longer has any more strong reference and hence will be deallocated. But Apartment has two strong references and one of which is by the property on Person instance that would be soon deallocated. I believe, this strong reference continue to remain after deallocation and goes out of reach by the code.
So, setting unit14A to nil will remove only one strong reference to Apartment instance and it should not be deallocated as there would be one more strong reference due to the above case.
But, as the document says Apartment instance promptly got deallocated. To me, this can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance. But I couldn't find any documentation to verify this.
So, How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Can someone help me to understand this?
Objective-C objects are reference counted, meaning that for each object, the system keeps track of how many other objects hold a reference to it. This is object's reference count. Two special messages, retain and release, are used to maintain the reference count behind the scene. Once reference count goes down to zero, the system deallocates the object.
ARC provides "magic" to make reference counting work in a declarative way. The compiler knows every strong reference in your code, so when you do this
myStrongRef = nil;
the compiler quietly inserts a call to release in front of the assignment:
[myStrongRef release];
myStrongRef = nil;
To me [deallocation of Apartment] can only happen if at the time of Person instance deallocation it sets its apartment property to nil, by that removing that strong reference on Apartment instance.
Setting a strong reference to nil one way of breaking a strong reference. It is sufficient, but it isn't necessary. The important thing about setting a strong reference to nil is not the act of setting itself, but what happens immediately before it: the instance referred to by the strong reference gets a release message, instructing it to decrement its reference count. That is precisely what ARC does behind the scene for you: it sends the release message to Apartment, without setting Person's reference to nil.
How does the Apartment instance get deallocated? What happened to the strong reference from the Person instance apartment property?
Once strong reference from Person has sent its release message to Apartment, that strong reference disappears. The actual pointer may be set to Apartment's address, but nobody cares about it, because the Person itself is unreachable.
The life of an object depends on it's reference count, not any actual pointer to the object.
Strong reference is a way of speaking, there is no difference between a strong and weak reference, they are just pointers. The difference is that when a strong reference is created the reference count of the object pointed to in incremented and when deleted the reference count is decreased. When an object's reference count would become zero the object is deallocated.
Your intuition is correct. When an object is being deallocated under ARC all the strong references it holds are first relinquished - essentially they are set to nil, but in practice the implementation may differ.
This is also what happens when a method returns, or a block of code containing declarations exits, all the strong references held in local variables are relinquished.
All the details can be found in the Clang documentation.
HTH
Obviously not before deallocation, but during deallocation.
When an object's reference count goes to zero, the deallocation process starts. The object is marked as "being deallocated". At that point, the object will die (unlike Java, where it can be recovered). If an object is marked like this, it cannot be assigned to weak references (they stay nil), or to strong references.
Then dealloc is called, that is the dealloc methods that you have written. After that, strong references are set to nil, reducing their reference counts, then associated objects are removed, and finally the memory for the object is deleted.

Objective-C weak reference zombie

I'm trying to create a zombie object to detect sending messages to a deallocated object.
Say i have a strong property object A with a weak reference to object B. When B is deallocated my weak reference becomes nil but calling a method e.g [obj1.obj2 somemethod] simply returns nil not causing a crash.
Is there a way to test zombies using weak references? I can only crash using unsafe_unretained.
Is there a way to test zombies using weak references
(I take it that by "zombies" you actually mean dangling pointers...)
Not directly, no. The whole point of ARC-weak references is that they prevent dangling pointers. (As you rightly say, they safely replace the potential dangling pointer with nil — and there's no penalty for sending a message to nil.)
The reason there can be dangling pointer crashes in real life is that most of Cocoa does not use ARC. (As you rightly say, it uses unsafe_unretained.)

Resources