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

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

    @pwc is correct in that you can't create a category for a class that you can't see.

    However...

    WHAT I AM ABOUT TO TELL YOU SHOULD BE USED STRICTLY AS AN EXERCISE IN LEARNING, AND NEVER IN ANY SORT OF PRODUCTION SETTING.

    1. Some runtime introspection reveals some interesting information. There are a number of classes that contain the word "Block". Some of them look promising: __NSStackBlock, __NSMallocBlock, __NSAutoBlock, and NSBlock.
    2. Some more introspection shows that the promising classes inherit from NSBlock

    So it looks like any block is going to be some instance or subclass of NSBlock.

    You can create a method on an object, like so:

    @implementation Foo
    - (void) doFoo {
      //do something awesome with self, a block
      //however, you can't do "self()".  
      //You'll have to cast it to a block-type variable and use that
    }
    @end
    

    Then at runtime, you can move that method to the NSBlock class:

    Method m = class_getInstanceMethod([Foo class], @selector(doFoo));
    IMP doFoo = method_getImplementation(m);
    const char *type = method_getTypeEncoding(m);
    Class nsblock = NSClassFromString(@"NSBlock");
    class_addMethod(nsblock, @selector(doFoo), doFoo, type);
    

    After this, blocks should respond to the doFoo message.

    USE AT YOUR OWN RISK, AND ONLY FOR EXPERIMENTING.

提交回复
热议问题