Obj-C: __block variables

后端 未结 3 1471
攒了一身酷
攒了一身酷 2020-12-20 02:06

Is it possible to assign a local variable a value whose scope is outside a block and have it retain its value? In particular, I\'m coding for iOS and I have a nested block i

相关标签:
3条回答
  • 2020-12-20 02:16

    you are simply defining your block but not calling it.

    Try this :)

    __block NSString *str;
    void (^someBlock)(id) =  ^(id param1)
    {
        str = @"iPhone";
    };
    someBlock(nil);
    [str getCharAtIndex:1];
    

    In this case I call it directly but usually the block itself is a parameter of some method or function.

    0 讨论(0)
  • 2020-12-20 02:19

    You're just defining that block, but not executing it. call someBlock(valueForParam1); to execute your block. Otherwise your str pointer points to some garbage and calling getCharAtIndex: crashes your app.

    0 讨论(0)
  • 2020-12-20 02:25

    First, str will get updated only after the block is executed. So unless you are using dispatch_sync for that block otherwise at this line:[str getCharAtIndex:1]; the block is unlikely to be executed and str will not get updated.

    Second, __block variable will not automatic retained by the block object if you are not using ARC. This means if you are not retain it, than by the time you accessing str, str may be a deallocated object and crash your app.

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