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

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

Consider this:

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


        
相关标签:
3条回答
  • 2021-01-05 05:00

    Yes, using __block will solve the problem.

    Without it, the Block gets a copy of the variable's value at the time the Block is created. (Which is "uninitialized" in this case.) With it, the Block (in essence) gets the variable itself, so that the value can be changed from within the Block. Thus it will also "track" changes made from outside.

    0 讨论(0)
  • 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] ...
    
    0 讨论(0)
  • 2021-01-05 05:13

    yes, I think declaring observer beforehand as __block id observer; should work.

    0 讨论(0)
提交回复
热议问题