Search code examples
objective-csyntaxobjective-c-blocksdeclared-property

Why can I not use dot notation in "independent" blocks?


About Objective-c blocks, the document I am reading said:

You can't refer to self in Independent block objects. if you need to, you must pass self object to the block as a parameter.

You can't access to properties of an object inside an Independent block using dot notation. If you need to do so, use setter and getter methods.

But I can write the following, and it runs as expected.

- (void)testing
{
    self.name = @"wahaha";
    void (^independentBlock)(NSString *arg) = ^(NSString *arg){
        self.name = @"";
        NSLog(@"%@ -- %@",arg, self.name);
    };

    a(@"abcd"); // abcd -- wahaha
}

So, why do the rules say dot notation cannot be used?


Solution

  • That quote seems to be incorrect, although they may be trying to get across the point that you shouldnt use self within independant blocks. in the example you gave it would be ok, but the problem arises when the block is kept around and used else where.

    if self is referenced inside a block, it keeps a strong reference to it, and if the block has a reference inside 'self' (whatever self may be) then you will have a retain cycle and a memory leak due to arc not being able to clean them up since they still have strong references to each other.

    you can fix this by declaring a variable pointing to self that is weak

    __weak <#TypeOfSelf#> weakSelf = self; //use weakSelf in your block