0

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?

Community
  • 1
  • 1
gaosboy
  • 3
  • 1

1 Answers1

0

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
Fonix
  • 11,447
  • 3
  • 45
  • 74
  • Does it mean that it is not true that self should be a parameter? – gaosboy Aug 14 '14 at 04:16
  • if self is passed in as a parameter then the block wont have a strong reference to it, so wont have retain cycle problems. the problem is a lot of blocks that are used like in animation blocks, you dont have the luxury of passing it in as a parameter so will have to use a weak self – Fonix Aug 14 '14 at 04:34