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

前端 未结 5 1506
梦如初夏
梦如初夏 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:19

    WRONG: A block winds up being an instance of type __NSGlobalBlock__, as seen in the     
    following snippet:
    
    int i = 0;
    id o = [class self];
    
    void (^aBlock)(void) = ^(void) {
    
        [o setValue:0];
    
        NSLog(@"Hello world %d", i);
    };
    
    // prints "type = __NSGlobalBlock__" 
    
    // Now it prints __NSStackBlock__ 
    // and when moved into HEAP prints __NSMallocBlock__
    
    NSLog(@"type = %@", [aBlock class]);
    

    It is only OKAY to say that a block winds up being an instance of type "NSGlobalBlock" unless there are no captured variables in the scope, otherwise it will be created in the STACK and when it is copied that will move the block into HEAP and every reference will be retained!

提交回复
热议问题