旧行李 2011-08-16 15:39 采纳率: 25%
浏览 171
已采纳

"阻碍"关键字是什么意思?

What exactly does the __block keyword in Objective-C mean? I know it allows you to modify variables within blocks, but I'd like to know...

  1. What exactly does it tell the compiler?
  2. Does it do anything else?
  3. If that's all it does then why is it needed in the first place?
  4. Is it in the docs anywhere? (I can't find it).

转载于:https://stackoverflow.com/questions/7080927/what-does-the-block-keyword-mean

  • 写回答

8条回答 默认 最新

  • 妄徒之命 2011-08-16 15:45
    关注

    It tells the compiler that any variable marked by it must be treated in a special way when it is used inside a block. Normally, variables and their contents that are also used in blocks are copied, thus any modification done to these variables don't show outside the block. When they are marked with __block, the modifications done inside the block are also visible outside of it.

    For an example and more info, see The __block Storage Type in Apple's Blocks Programming Topics.

    The important example is this one:

    extern NSInteger CounterGlobal;
    static NSInteger CounterStatic;
    
    {
        NSInteger localCounter = 42;
        __block char localCharacter;
    
        void (^aBlock)(void) = ^(void) {
            ++CounterGlobal;
            ++CounterStatic;
            CounterGlobal = localCounter; // localCounter fixed at block creation
            localCharacter = 'a'; // sets localCharacter in enclosing scope
        };
    
        ++localCounter; // unseen by the block
        localCharacter = 'b';
    
        aBlock(); // execute the block
        // localCharacter now 'a'
    }
    

    In this example, both localCounter and localCharacter are modified before the block is called. However, inside the block, only the modification to localCharacter would be visible, thanks to the __block keyword. Conversely, the block can modify localCharacter and this modification is visible outside of the block.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line