why it is recommended to use the _weak reference with delegates - ios

Hi every one whether some one will elaborate me that why it is recommended to use the _weak reference for delegates and not the strong reference? though we can also use the strong reference for delegates. Some one will please tell me with the better and descriptive example with simple way that in which situations should we use the strong reference and in which situations should we use the _weak reference for the delegates.
I went through one of the related question on stack overflow
Is it ever Ok to have a 'strong' reference for a delegate?
but it did not clear my concept properly.
Any help will be highly appreciated !!
Thanks.

Using __strong on delegate is very easy to create retain cycle:
say A has a strong reference to B, and some object set A as a delegate of B, if the delegate is strongly referenced, then, a retain cycle is formed.

Yes, It's east to creat a retain cycle while using __strong on delegate.
Addtionally, in ARC, we using weak on delegate,while the object using the delegate is released,the delegate will be nil automatically.

Related

Why does the weak/strong dance solve this strong reference cycle? I don't understand

Ok, I understand the reason for the strong weak dance.
One example being, let's say B strongly references a block, and we set that block inside B to strongly reference itself(B). We now have B strongly referencing our block, perhaps our block is allocated to the heap to run later (async perhaps), and our block is strongly referencing B. Let's say only some object A strongly reference B. If we kill A, then B -> block AND block -> B. Strong reference cycle and memory leak.
Another way we might see this is A strongly references B. B strongly references C. Perhaps C has a block property, and B says C.block = ^{ self.blah = blah }. Now we have B strongly referencing C, and C strongly referencing B. A is killed, and we have a strong reference cycle once again. Correct me if I'm wrong on any of this.
Now I'm seeing a strong reference cycle that in my mind should not be a strong reference cycle.
I have a class, let's call it A. A has a function fooBar. Inside fooBar, we call
[[MySingleton sharedInstance] doSomeBackgroundJazz: ^{
self.blah = blah;
}];
We're seeing a strong reference cycle and A isn't getting deallocated. Now, in my mind, A does not have a strong reference to MySingleton. Maybe for the duration of fooBar it does, but the class itself does not. But when fooBar is done, its removed from the stack, and there is no reference to MySingleton any longer. Correct me if I'm wrong at any point here. Now, we know our block code that is in [MySingleton doSomeBackgroundJazz] strongly references A. However, why does this matter? A doesn't reference MySingleton. MySingleton strongly references A. No need for the weak strong dance.
However, when I put the weak strong dance in.. our problems our alleviated. A no longer sticks around. (Right now the real world problem we are having is leaving a view and coming back, keep creating a new view plus retaining the previous ones. Each one listens for a notification, and does an API call. So we can potentially have dozens of API calls going out every second).
Why is the weak strong dance solving this?
Assuming A is your caller to -doSomeBackgroundJazz:
It appears your MySingleton class stores your block off into a property.
Because you captured self (A) in your block, when the block is stored into a property it is also retained.
So this means that as long as your singleton instance (sharedInstance) is retained, it's block property is retained, and therefore your captured A is retained.
It doesn't matter that A doesn't retain the sharedInstance, it clearly is hanging around for whatever reason.
The rule of thumb is to cast self with __weak whenever the block is going to be stored into a property. However it doesn't hurt to always make a __weak cast anyways, there rarely should be the case where you want a block to retain an object

iOS. what does "self" mean in a dispatched block?

I have see many blocks use "self.xxx" in a block, then how can I make sure the "self" is the instance I want?
Example:
I am in instance A, whose delegate is B.
And then I call [A.delegate dispatchBlockTest]
The dispatchBlockTest in instance B is like this:
dispatch_async(dispatch_get_main_queue(DISPATCH_UEUE_PRIORITY_DEFAULT, 0),^{
[self printClassName];
});
});
Then, the "self" in the block is definitely B? not A?
Any sort of help is appreciated, thanks.
Fonix's comment is right on. For more information, you can check out this page from the official Apple docs. Specifically take a look at the "Blocks Can Capture Values from the Enclosing Scope" section. The meaning of a variable in a block is always "captured" when the block is declared, so local variables, properties, and references to self are all based on the scope of where the block is declared (in your case, the scope in class A) and NOT based on where the block is called (in your case, class B).
On a side note, one subtle thing it's worth knowing about using self with blocks is that you can create a type of memory leak known as a strong reference cycle or a retain cycle (Check out the section on weak properties here for an explanation). In general, it's good practice to always use a weak reference to self in blocks (Apple has a good example here). Most of the time, using self in a block won't create a strong reference cycle, but if you always use a weak reference to self in a block, you don't have to think about whether or not you risk a reference cycle.

Does a property require strong keyword?

Properties are now synthesized by default. The compiler will use the property name plus the underscore prefix to create the ivar. And instance variables have strong storage type by default, so it means property is by default strong. So why does property require a strong keyword (seen a lot many people specify it explicitly). Are there be cases where property is weak? Sorry, if it seems to be a noob question.
Edit: IBOutlet, delegates should be weak, any other property apart from that which should be weak.
Properties are strong and atomic by default.
Typing it in explicitly is more for readability purposes than anything else.
There are times when you should use weak properties. Delegates, IBOutlets, etc...
But you have to declare these explicitly.
I would also add to the other answers that block properties require you to specify ownership explicitly.
Usually you need copy for blocks (strong works correctly under ARC but you must use copy under MRC)
Views and Delegates should almost always be weak.
Views should only have a strong reference from superviews.
Delegates should just have to care that their work was done.
Generally weak references are seen automatically from IBOutlets since the view itself holds a strong reference. There are many other use cases. This is to prevent retention cycles.
http://www.quora.com/What-is-the-difference-between-strong-retain-nonatomic-etc-in-objective-C-iOS-property
Avoiding circular retention using ARC (strong/weak), learning some basics
EDIT:
More information can be found here and should be fully understood before looking specifically for examples of weak references besides IBOutlets and delegates. Understanding why each of those are generally weak references would lead to an explanation of what should or shouldn't be weak.
Differences between strong and weak in Objective-C

When accessing properties, what is the different between dot syntax and "->" [duplicate]

This question already has answers here:
What is the difference between '->' (arrow operator) and '.' (dot operator) in Objective-C?
(3 answers)
Closed 8 years ago.
I have a block that uses a weak reference of itself to access properties inside the block. When accessing those properties, I use
__weak ViewController *weakSelf = self;
someBlock = ^{
ViewController *safeSelf = weakSelf;
weakSelf.someObject
safeSelf->someObject
}
When using weakself, what is the reason for using dot syntax and for the strong reference from the weak reference, to use -> syntax
The object->iVar syntax accesses the instance variable directly, without using the property.
You should forget you ever saw this, and never, ever use it (Until you get to the point where you understand this stuff cold, and find the .01% edge case where you need it.)
That syntax allows you to reach into another object and access it's instance variables directly, which is bad practice. Properties allow you to control access to an object's public interface, and maintain the encapsulation of the object.
The __weak weakSelf convention is for code blocks. Code blocks capture a strong reference to variables from their enclosing scope, and can cause a retain cycle, since your object has a strong reference to the block and the block has a strong reference to the object through the reference to self. By creating a weak variable weakSelf, you make the block's reference to the object that owns it weak, and avoid the retain cycle.
-> directly accesses the instance variable. weakSelf.someObject is equivalent to [weakSelf someObject].
You probably don't want to use -> for this unless you have a specific reason, like performance, or to skip KVO. Generally, it is preferred to use property access.
A side note: you should not use weakSelf for anything besides creating safeSelf. After that, you should get everything you need from safeSelf. (weakSelf can turn nil at any point if there are no longer strong references to the object.)
weakSelf.someObject
safeSelf->someObject
They are both silly. Having established a strong safeSelf in the first line of your block, you should make sure it is not nil and then use it exclusively, with normal property (dot) syntax so that you pass through the accessor method and get whatever benefits it has (which might include thread safety):
safeSelf.someObject
You definitely do not want to use ->. The concern here is that your reference to self might be nil - and using -> on a nil object is a disaster.

Retaining property in arc

I am new at objective-c.I have a question .I know little about Retain .All i know is Retaining an object creates a strong reference, and an object cannot be deallocated until all of its strong references are released. If two objects retain each other, neither object ever gets deallocated because the connection between them cannot be broken. In ARC we can not retain a object. But we can retain a property.
What is the difference between retaining a object and retaining a property.
Thank You
Happy coding.
After searching so many articles and links, I decided to put all the attributes information together:
atomic //default
nonatomic
strong=retain //default
weak
retain
assign //default
unsafe_unretained
copy
readonly
readwrite //default
Many thanks to all the people who give best answers here!!
a property is retain, mean the class own the property NSObject, that's nothing about ARC. ARC just do auto release reference count.

Resources