ARC, self and blocks

后端 未结 3 1271
一个人的身影
一个人的身影 2021-02-06 06:34

I thought I understood the usage of self in a block that is copied is a no no.

But in an attempt to clean my code i enabled a bunch of warnings in Xcod

3条回答
  •  伪装坚强ぢ
    2021-02-06 07:05

    Strong reference to a weak reference retains an object. It could be important in following case

    __weak typeof(self) weakself = self;
    [aClass doSomethingInABlock:^{
    
         [weakself allocateSomething]; // (1)
         // ..... code (2)
         [weakself freeSomething];  // (3)
    }];
    

    If Weak receiver will be unpredictably set to nil in line (2) resources could be successfully allocated in (1) but not freed in (3). To avoid such problems strong reference could be used.

    [aClass doSomethingInABlock:^{
         typeof(self) selfref = weakself; 
         [selfref allocateSomething]; // (1)
         // ..... code (2)
         [selfref freeSomething]; // (3)
    }];
    

    Now if selfref is not nil in (1) it will also be valid in (2) and (3).

提交回复
热议问题