探究Block之MethodSignature

在iOS开发中,Block是常用的数据类型,Block的源码是开放的,对于Blcok的其他探究可以查看这篇文章深入研究Block捕获外部变量和__block实现原理.先来简单介绍一般MethodSignature的获取和配合Invocation的使用.

方法签名

Person类为例,该类只有一个类方法和对象方法:

@interface Person : NSObject

- (void)say:(NSString *)name;
+ (void)setAge:(int)age;

@end

@implementation Person

- (void)say:(NSString *)name
{
    NSLog(@"say : %@",name);
}

+ (void)setAge:(int)age{
}
@end

一般我们获取对象方法和类方法的签名可以这样:

/// 根据方法签名获取TypeEncoding
NSString *getMethodSignatureTypeEncoding(NSMethodSignature *methodSignature){
    NSMutableString *str = @"".mutableCopy;
    const char *rtvType = methodSignature.methodReturnType;
    [str appendString:[NSString stringWithUTF8String:rtvType]];

    for (int i = 0; i < methodSignature.numberOfArguments; i ++) {
        const char *type = [methodSignature getArgumentTypeAtIndex:i];
        [str appendString:[NSString stringWithUTF8String:type]];
    }
    return [str copy];
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {

    // 对象方法签名
    NSMethodSignature *instanceMethodSignature = [Person instanceMethodSignatureForSelector:@selector(say:)];
    // 类方法签名
    NSMethodSignature *classMethodSignature = [Person methodSignatureForSelector:@selector(setAge:)];
    NSLog(@"instanceMethodSignature : %@ \n classMethodSignature : %@",getMethodSignatureTypeEncoding(instanceMethodSignature),getMethodSignatureTypeEncoding (classMethodSignature));

    }
    return 0;
}

/*
  打印结果:
 instanceMethodSignature : v@:@ 
 classMethodSignature : v@:i
*/

方法签名记录着一个方法的返回值类型编码(TypeEncoding)、形参个数、每一个形参的类型编码.有了方法签名之后,可以通过类型编码来反解出真实类型,类型的映射关系可以查看官方资料.
根据Personsay:方法获得的方法签名结果为v@:@,v代表void类型,@代表对象类型,对应的是隐藏参数self,:代表SEL类型,对应的是隐藏参数_cmd,@对应的是第一个形参.每一个OC的类方法或对象方法都会包含两个隐藏参数self_cmd,并且它们的位置是固定的,在invocation对象中的索引分别是0和1,返回值是不占索引的,需要额外获取.

配合NSInvocation使用

有了方法签名之后,我们可以组装一个NSInvocation对象并调用对应方法,这里就简单直接设置了索引2为name了,一般都会动态循环设置设置,例如JSPatch.

Person *p = [Person new];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:instanceMethodSignature];
invocation.selector = @selector(say:);
NSString *name = @"abc";
[invocation setArgument:&name atIndex:2];
[invocation invokeWithTarget:p];
/*
  打印结果: say : abc
*/

如果不是block对象,invocation必须要设置selector,原因跟类的方法结构有关,关于类的方法结构<<深入解析 ObjC 中方法的结构>>这篇文章分析的非常深入.Aspects也对NSInvocation做了分类来获取方法签名并获取对应实参.

Block的方法签名

Aspects 源码中,有一段获取Blcok方法签名的代码比较有意思:

typedef NS_OPTIONS(int, AspectBlockFlags) {
    AspectBlockFlagsHasCopyDisposeHelpers = (1 << 25),
    AspectBlockFlagsHasSignature          = (1 << 30)
};
typedef struct _AspectBlock {
    __unused Class isa;
    AspectBlockFlags flags;
    __unused int reserved;
    void (__unused *invoke)(struct _AspectBlock *block, ...);
    struct {
        unsigned long int reserved;
        unsigned long int size;
        // requires AspectBlockFlagsHasCopyDisposeHelpers
        void (*copy)(void *dst, const void *src);
        void (*dispose)(const void *);
        // requires AspectBlockFlagsHasSignature
        const char *signature;
        const char *layout;
    } *descriptor;
    // imported variables
} *AspectBlockRef;

static NSMethodSignature *aspect_blockMethodSignature(id block, NSError **error) {
    AspectBlockRef layout = (__bridge void *)block;
    if (!(layout->flags & AspectBlockFlagsHasSignature)) {
        NSString *description = [NSString stringWithFormat:@"The block %@ doesn't contain a type signature.", block];
        AspectError(AspectErrorMissingBlockSignature, description);
        return nil;
    }
    void *desc = layout->descriptor;
    desc += 2 * sizeof(unsigned long int);
    if (layout->flags & AspectBlockFlagsHasCopyDisposeHelpers) {
        desc += 2 * sizeof(void *);
    }
    if (!desc) {
        NSString *description = [NSString stringWithFormat:@"The block %@ doesn't has a type signature.", block];
        AspectError(AspectErrorMissingBlockSignature, description);
        return nil;
    }
    const char *signature = (*(const char **)desc);
    return [NSMethodSignature signatureWithObjCTypes:signature];
}

_AspectBlock结构体是不是很熟悉? 对,就是跟Block指向的结构体是基本一样的!为什么说基本一样的呢?因为官方文档里面block是长这样子的:

struct Block_layout {
    void *isa;
    int flags;
    int reserved;
    void (*invoke)(void *, ...);
    struct Block_descriptor *descriptor;
    /* Imported variables. */
};

struct Block_descriptor {
    unsigned long int reserved;
    unsigned long int size;
    void (*copy)(void *dst, void *src);
    void (*dispose)(void *);
};

先来分析一下这段代码,AspectBlockFlags枚举是block的标记.aspect_blockMethodSignature方法先强制将Blcok转换成了AspectBlockRef类型指针,然后利用flags判断是否存在方法签名,再获取block的descriptor,descriptor结构体的copy或者signature存在着方法签名.但是由于全局block和堆block存在的位置不同,所以需要判断.如果是全局block,则方法签名存在于signature上,如果是堆block,则存在于copy上.我们可以来验证一下:

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // _NSConcreteMallocBlock 堆block
        __block int a = 0;
        id mallocBlock = ^(int b){
            a ++;
            NSLog(@"mallocBlock: a = %d ,b = %d",a,b);
        };

        // _NSConcreteGlobalBlock 全局block
        id globalBlock = ^(NSString *name){
            NSLog(@"globalBlock : name = %@",name);
        };

        NSMethodSignature *mallocBlockSignature = aspect_blockMethodSignature(mallocBlock, NULL);
        NSMethodSignature *globalBlockSignature = aspect_blockMethodSignature(globalBlock, NULL);

        NSLog(@"mallocBlockSignature : %@ \n globalBlockSignature : %@",getMethodSignatureTypeEncoding(mallocBlockSignature),getMethodSignatureTypeEncoding (globalBlockSignature));

    }
    return 0;
}

/*
  打印结果: 
 mallocBlockSignature : v@?i 
 globalBlockSignature : v@?@"NSString"
*/

aspect_blockMethodSignature方法的desc += 2 * sizeof(void *);处打断点,然后发现全局block执行了这句,而堆block没有执行这句.

栈block由于在ARC下无法验证,所以目前不知道.

我们发现block的方法签名和对象的方法签名不一样,第二位和第三位不再是@:了,而是被@?这个block标记代替了.再看看类型编码,基本数据类型在两者情况下是一样的,但是对象类型在block的方法签名对应的@后面会标明对象类型.

调用block

既然获取到了block的方法签名,这样就可以组装一个NSInvocation对象来调用block.

__block int a = 0;
id mallocBlock = ^(int b){
    a ++;
    NSLog(@"mallocBlock: a = %d ,b = %d",a,b);
};
NSMethodSignature *methodSignature = aspect_blockMethodSignature(mallocBlock, NULL);
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
int b = 1;
[invocation setArgument:&b atIndex:1];
[invocation invokeWithTarget:mallocBlock];
/*
  打印结果: mallocBlock: a = 1 ,b = 1
*/

由于block的方法签名最前面除了返回值以外只有@?,所以所以需要从1开始设置参数.

总结:我们可以利用block来表示一个方法的实现,block的参数类型和个数可以根据实际的方法来动态一一对应.这样做的好处是如果方法的参数个数和类型是不确定的,利用block可以将整个方法的实现替换成一个block,可以达到替换任意方法的目的,这也是Aspects这个AOP实现框架的重要一部分.

你可能感兴趣的:(探究Block之MethodSignature)