Alternative for strongSelf in a block

Code snippets By 2 years ago

One of the most common practices of using “self” inside a block is with the weakSelf strongSelf strategy.

Here’s an example:

__weak typeof(self) weakSelf = self;

[self doSomethingWithCompletionHandler:^{
	
	typeof(self) strongSelf = weakSelf;
	
	[strongSelf aMethod];
	[strongSelf anotherMethod];
}];

This works fine, but not many know you can actually redefine “self” inside a block as so:

__weak typeof(self) weakSelf = self;

[self doSomethingWithCompletionHandler:^{
	
	typeof(self) self = weakSelf;
	
	[self aMethod];
	[self anotherMethod];
}];

The advantages to using this is now you can more easily copy and paste code in and out of your blocks, without needing to retype “self” and “strongSelf”

  • daniel

    Can you share an example in swift please?

  • Minu

    Dear Tom,
    First of all I want to introduced my self my name is Minu(minuturcin@yahoo.com) , I am mechanical engineer and am 56 years old.

    I looking for some example to transform text in pdf and after that attached to emai i found your question from 2013 .

    Please can you help me with this matter .It is very urgent matter .

    I appreciate your answer .

    Thank you very much ,

    best regards,