Search code examples
iosobjective-c-blocksself

Is it correct to use local variable name "self" in blocks?


I`ve found that construction __strong typeof(self)self = weakSelf.

It allows remove NSAssert macro self catching, but I am in doubt is it right to use it in that way?

__weak typeof(self)weakSelf = self;
self.signupBlock = ^{
    __strong typeof(self)self = weakSelf;
    NSLog (@"%d", self.property)
    NSAssert((self.property > 5), @"Some message");
}

Pls advice.

Sorry, I had to say first that using of __strong typeof(self)strongSelf = weakSelf;

construction results to warnings and I suppose to mem cycle, when NSAssert macro used, because it contains self in.


Solution

  • self is just an variable name, so it's perfectly fine to redefine it locally. It might be even preferred to

    __strong typeof(weakSelf) strongSelf = weakSelf;
    

    because

    • it makes for easily readable code
    • it prevents you for mistakenly referencing "real" self and potentially creating retain cycles.

    Additionally, you might want to look at answers to this question for discussion when to use weak / strong self in blocks, and libextobjc library for neat @weakify / @strongify macros.