roMoon
roMoon

Reputation: 91

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.

Upvotes: 1

Views: 51

Answers (1)

ezig
ezig

Reputation: 1229

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.

Upvotes: 2

Related Questions