Understanding weak and unowned reference in Swift under the hood - swift

I want fully understand what going inside weak and unowned referance in Swift.
For this i read MikeAsh and got some questions.
What already known:
when there is no weak (and, i suppose, unowned) object reference, the strong reference counter is stored directly in the memory area of the object
when a weak link appears, the second word in the object memory is reused to reference the side table
side table has link to the object
weak link refers to this side table
And what i want to clearify:
What else side table store inside except link to the object and number of strong reference?
Is unowned reference link to the side table too? If not and unowned link refers to the object memory what about performance between weak and unowned ?

Okay, i found out.
Unowned link points to the object as well as strong.
Unowned link faster than weak.
Side table stores strong RC, weak RC, unowned RC, link to the object and some flags

Related

Difference Between weak & unowned in respect to ARC memory management in Swift 3.1 [duplicate]

This question already has answers here:
What is the difference between a weak reference and an unowned reference?
(7 answers)
Swift. Is the (absolutely) sole specific advantage of unowned over weak, performance?
(4 answers)
Closed 5 years ago.
I am working on Swift and I have little bit confusion on usage of unowned and weak keywords for memory management in Swift.
Can any one help me to understand where to use unowned ?
Thanks in advance!
The most important difference is that unowned variables are very dangerous in Swift.
weak is an optional type, unowned is NOT.
This means that you can create code that uses weak as part of the logic. (think of asynchronous actions that take place only if a view controller is still being shown on the screen, when the code is ran, if the reference is "weak" it will fail silently without causing any other issues if the code is written correctly)
On the other hand, when a variable is unowned you are basically saying that this variable will always refer to something. And unlike weak, if you call it and there's nothing it will crash.
You generally never wanna use unowned. (I haven't come across any case where I had to). On the other hand, "weak self" variables are quite common when writing blocks.
You can see a good explanation on this question:
Shall we always use [unowned self] inside closure in Swift
EDIT: Actually, check the first and second most voted answers. They provide a clear explanation on WHEN to use unowned and how it works. The second even has pictures!
As per apple docs
There are some pretty good examples given on the developer website, check this link
As far as blocks are concerned as per Apple Docs:
Define a capture in a closure as an unowned reference when the closure
and the instance it captures will always refer to each other, and will
always be deallocated at the same time.
Conversely, define a capture as a weak reference when the captured
reference may become nil at some point in the future. Weak references
are always of an optional type, and automatically become nil when the
instance they reference is deallocated. This enables you to check for
their existence within the closure’s body.
To conclude Use a weak reference whenever it is valid for that
reference to become nil at some point during its lifetime. Conversely,
use an unowned reference when you know that the reference will never
be nil once it has been set during initialization.”

What good are unowned references?

Weak and Unowned references are used to prevent retain cycles in the situation where two objects each hold a reference to the other. I get the use of weak but I do not get the use of unowned. Here is Apple's example of a situation where one of the two objects should use an unowned reference:
class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
}
The idea is that a credit card cannot exist without a customer. Therefore a credit card can dispense with the optional unwrapping that the use of a weak reference would entail, and can instead use an unowned reference. Hmmm ... so why not use a strong reference? If all other references to the customer were to go away (which is not supposed to happen?) then the credit card's use of an owned reference would result in a crash; whereas its use of a strong reference would result in a memory leak. Huh? A choice between two evils? Better to crash because that is more likely to be noticed during development and testing?
Please help with some insight. Thanks.
Better to crash because that is more likely to be noticed during development and testing?
Yes.
Well, not exactly.
The idea is that your app's design should ensure that no CreditCard instance outlives it's respective Customer instance. When you use unowned, you trust yourself to have a design in play that logically guarantees a crash-free execution.
Now, why would anyone ever use unowned over weak? Simple! unowned removes the whole hassle of Optional unwrapping, and if you know that your CreditCard instance will never outlive it's respective Customer instance, then you should use unowned by all means.
unowned is actually much better than weak, in those situations where it is appropriate (i.e. it is certain that the unowned object will not go out of existence), because:
A weak reference must be an Optional, which may need unwrapping, and
A weak reference entails large amounts of overhead in order to track the reference and change it to nil if it is deallocated, whereas an unowned reference entails zero overhead.
It's actually not a problem because as it stands, the unowned reference does not create any sort of strong reference cycle. When the Customer object is deallocated, its CreditCard will be immediately deallocated as well. Your CreditCard will never get a chance to reference that deallocated Customer.
Very interesting question. Here is some difference between Weak and Unowned References according to Apple's documentation.
Weak References
A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle.
Unowned References
Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime.
Your question's answer :
weak can become nil, whereas unowned is presumed to never become nil, therefore weak will be optional where as unowned does not need to be optional.
In this case Customer may or may not have CreditCard but no CreditCard should exist without Customer.
Okay, I finally get it:
The last reference to Customer (other than Credit Card's) is set to nil.
ARC checks the Customer's reference count:
Credit Card has a strong reference - Customer's reference count will be 1 so ARC will not deallocate it. Result - memory leak.
or, Credit Card has an unowned reference - Customer's reference count will be 0 so ARC will deallocate it. Doing so will cause Credit Card's reference count to go to 0 causing it to be deallocated. Hence, Credit Card will never have an opportunity to dereference its now nil unowned reference. Result - no crash.
So, if we have designed our code such that holder of the reference (CreditCard) is guaranteed to be deallocated when the referenced object (Customer) is deallocated then we have the kind of scenario wherefore unowned references were designed.
Thanks #Bob
Quick search on this topic revelead this link to another SO answer.
Basically weak references can or cannot be nil, where as unowned references assume that it will never be nil.
You can learn more about them in the Apple docs.
I'm guessing the reasoning behind using an unowned in this case is solely because the unowned is presumed to never be nil (without a customer).

Swift, two issues. 1) weak var 2) bang operator for #IBOutlet

Per:
#IBOutlet weak var nameLabel: UILabel!
Whenever I declare my IBOutlets, i just use var instead of weak var. But I've recently come across a few code templates that use weak var. Why do they do it? What's the added benefit?
Why is there a bang operator at the end of UILabel. I know it's required and i go along w/ it, but just asking it now.
Thanks in advance.
Swift IBOutlet are weak by default (but others properties are strong by default). So both writing are the same.
You have more details about the difference between weak and strong here
According to apple documentation
When you declare an outlet in Swift, you should make the type of the
outlet an implicitly unwrapped optional (!). This way, you can let the
storyboard connect the outlets at runtime, after initialization.
The outlets are weak since the view elements are owned (strongly) by the view. I think it's technically OK for your view controller to have a strong reference too, but not necessary.
Weak variables are optional since they can be nil. You can declare your outlets with ? instead but that means using force-unwrapping or optional binding every time. Declaring them as implicitly-unwrapped optionals with ! is just a convenience.
You use weak when referring to IBOutlets because so long as the object remains in its superview there will be a strong reference to it. See weak or strong for IBOutlets.
Next, the bang operator indicates that the IBOutlet is an explicitly unwrapped label. With the bang operator, it guarantees that the object will exist, so when referencing it, you can simply reference it like this:
someLabel.text = "some text"
However, you can make them IBOutlets optional:
#IBOutlet weak var someLabel: UILabel?
But you must use ? when accessing them
someLabel?.text = "some text"
#gregheo's response is the best explained, to further elaborate: if you consider ownership in this situation the View object referred to by the #IBOutlet usually shouldn't be owned by the View Controller referring to it.
Rather it should be owned by its superview wherever it may be in the tree (which happens strongly by UIView.subviews). The View Controller instead owns the very root of it's View Tree strongly (UIViewController.view). weak explicitly declares a non-owning reference that may become nil at different points in the View Controller's life.
Here I would offer an alternative to using !: using an implicitly unwrapped optional reference is a dangerous practice that weakens the tools Swift offers us. A View Controller which is loaded from Xib or Storyboard includes in its lifetime a regular time after being created and before it's View has been loaded where the #IBOutlet reference is nil, every time. To assume no one will operate on the member during that time means not using the Swift grammar and compiler's feedback to our advantage.
Additionally #IBOutlets are a powerful tool that enables a flexible, visually focused approach when designing a screen or view. It is common practice to have your View Controller expose #IBOutlets for all information it has available, regardless of whether or not it is known that it will be used and separately deciding which to actually connect and use when building and iterating on the View from within Interface Builder.
Additionally-additionally if your View should be flexible enough to be instantiated from Xib/Storyboard AND from code, depending on how you decide referenced subviews should be instantiated and connected they may or may not be available immediately.
For the reasons above I define mine: #IBOutlet weak var nameLabel: UILabel?

differences between weak and assign property?

I have few questions.
1)where assign property will take memory as we dont need to release for reducing reference count?
2)what is the difference between auto zero reference and non-auto zero reference?how does it work? how will take memory?
weak applies to objects (they have reference counts and all the stuff), but weak references don't increase refcount. But once the object is deallocated (from anywhere in the code), any weak reference to that object is set to nil. This is extremely useful, because if you use only strong and weak references, you can't end up with an invalid pointer (pointer to an already deallocated object).
assign does absolutely nothing with the reference, it is usually used for ints, floats and other non-object types. You can of course assign an object reference to such a variable, but if the object is deallocated, you will still have a pointer to it's memory (which is garbage now, and will hurt you when you use it).
Your concerns about "memory use" are weird - references don't take memory, object do. But you can't deallocate an object if you are going to use it. The simple rule for beginners is: for objects, use strong references whenever you can. When you have a reason not to use strong reference, use weak (usually for delegates and datasources). For primitive types (int, float, CGRect, ...) use assign, because they are not objects.
assign is like weak but there's no zeroing of the pointer when it leaves the heap. So, it's not as safe as weak.

How do weak and strong references look like in objective-c?

Wikipedia states "In computer programming, a weak reference is a reference that does not protect the referenced object from collection by a garbage collector". How do those two types of references look like in code? Does a weak reference is a reference made by an autoreleased message?
The following answer is for the case when there is no garbage collection (such as on iOS).
In the case of garbage collection, there is actually a keyword (__weak) to create a weak reference.
A "weak" reference is a reference that you do not retain.
You need to use these weak references to break up cycles. A common case is a child object that needs a reference to its parent object. In this scenario, the parent would retain a reference to the child object, and the child object has a reference to its parent, but does not retain it. This works because the child object only needs to exist as long as the parent object does.
Does a weak reference is a reference made by an autoreleased message?
Not really, that would be a "very weak reference" ;-)
Auto-released stuff goes away when the call stack is unwound (at the end of every event loop for example). If you need anything to be less temporary, you need to retain a reference (or like in the case above be sure that some other part retains it sufficiently).
A weak reference is a reference that isn't strong enough to force an object to remain in memory while a strong reference forces an object to remain in memory.
If you have created weak reference to any variable, you may get nil for that.
UITableViewDelegate, UIScrollViewDelegate, etc are examples of weak references.
Example of Strong reference :
MyClass *obj1 = [[Myclass alloc] init];
Myclass *obj2 = obj1;
Here obj2 has strong reference to obj1 mean if you remove obj2 from memory then obj1 also get removed.