Is it possible to create a category of the “Block” object in Objective-C

前端 未结 5 1492
梦如初夏
梦如初夏 2021-02-07 20:40

I would like to add functions by creating a category for Objective-C Blocks.

__block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return         


        
5条回答
  •  攒了一身酷
    2021-02-07 21:18

    The simple answer is no. A __block variable is a C level object not an Objective C object. You can call [aBlock copy] but this invokes a C function block_copy() not the nsobject copy method. So the __block type is a C type and therefore you can't add categories.

    correction:__block is an identifier in the C compiler not a typedef.

    I'm not sure if this will achieve what you think it will, infact I'm not even quite sure what it does:

    __block int (^aBlock)(int) = ^int( int n ){
    if( n <= 1 ) return n;
    return fib( n - 1 ) + fib( n - 2 );
    };
    

    the __block identifier tells the complier that the variable should be mutable in referencing blocks and should be preserved if any referencing block is copied to the heap. what confuses me about your code is that __block is usually used to wrap a variable, not a block itself.

提交回复
热议问题