iOS NSMethodSignature (or encoding) of NSBlock

前端 未结 1 1071
孤城傲影
孤城傲影 2021-02-04 19:46

I need a way to check the number of arguments and argument types of a given block at runtime (I need this for some object mapping library I\'m currently writing, I\'m mapping St

相关标签:
1条回答
  • 2021-02-04 20:19

    Using CTBlockDescription, you can get all the runtime information you need as a NSMethodSignature object. Usage is straightforward:

    NSString * (^block)(int, NSArray *) = ^NSString * (int i, NSArray * a){
        return @"Oh, yeah!";
    };
    NSMethodSignature *signature = [[[CTBlockDescription alloc] initWithBlock:block] blockSignature];
    NSLog(@"signature %@", [signature debugDescription]);
    

    This will output the following signature:

    signature <NSMethodSignature: 0x6844900>
        number of arguments = 3
        frame size = 12
        is special struct return? NO
        return value: -------- -------- -------- --------
            type encoding (@) '@'
            flags {isObject}
            modifiers {}
            frame {offset = 0, offset adjust = 0, size = 4, size adjust = 0}
            memory {offset = 0, size = 4}
        argument 0: -------- -------- -------- --------
            type encoding (@) '@?'
            flags {isObject}
            modifiers {}
            frame {offset = 0, offset adjust = 0, size = 4, size adjust = 0}
            memory {offset = 0, size = 4}
        argument 1: -------- -------- -------- --------
            type encoding (i) 'i'
            flags {isSigned}
            modifiers {}
            frame {offset = 4, offset adjust = 0, size = 4, size adjust = 0}
            memory {offset = 0, size = 4}
        argument 2: -------- -------- -------- --------
            type encoding (@) '@'
            flags {isObject}
            modifiers {}
            frame {offset = 8, offset adjust = 0, size = 4, size adjust = 0}
            memory {offset = 0, size = 4}
    
    0 讨论(0)
提交回复
热议问题