Capturing a variable in a Block when the Block is in the initializer

后端 未结 3 1436
广开言路
广开言路 2021-01-05 04:45

Consider this:

id observer = [[NSNotificationCenter defaultCenter] 
    addObserverForName:MyNotification 
                object:nil 
              


        
3条回答
  •  渐次进展
    2021-01-05 05:09

    As explained in the answers to

    Why doesn't Remove Observer from NSNotificationCenter:addObserverForName:usingBlock get called,

    you have to

    • add __block, so that the block will refer to the initialized variable, AND
    • add __weak, to avoid a retain cycle. (The latter applies only to ARC. Without ARC, the block does not create a strong reference to a __block variable.)

    Therefore:

    __block __weak id observer = [[NSNotificationCenter defaultCenter] ...
    

提交回复
热议问题