Question

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

Was it helpful?

Solution

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.

OTHER TIPS

-> 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top