[iOS][Block]block不定参数的回调方式

前言

上一篇文章讲了对于MVVM的理解,最后提到了会写一些模仿RAC的小技巧.在后面的研究中,我发现在利用RAC实现登录的demo中有这样一行代码:

///监听文本框输入状态,确定按钮是否可以点击
    RAC(_loginBtn,enabled) = [RACSignal combineLatest:@[_accountTF.rac_textSignal,_passwordTF.rac_textSignal] reduce:^id _Nullable(NSString * account,NSString * password){
        return @(account.length && (password.length > 5));
    }];

这里绑定了账号和密码两个输入信号,然后在reduce这个block中回调了accountpassword这两个参数,很好奇为啥这个block能准确的回调出两个参数,于是去看了一下实现源码,然后自己也写出了一个简单的实现.
先看一个基础的例子.

最基本的方式

首先我们定义一个block:

typedef id(^TBlock)() // 第二个括号不能加void

注意:这里XCode会警告你要加void,但这里不能加,因为无参数是添加不定参数的前提.如果要消除这个警告.可以用下面的代码包裹:

_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wstrict-prototypes\"") \
typedef id(^TBlock)();
_Pragma("clang diagnostic pop")

然后我们写一个这样的方法:

- (void)numbersOfArguments:(NSUInteger)count block:(TBlock)block{
    if (!block) {
        return;
    }
    switch (count) {
        case 0:
        {
            block();
        }
            break;
        case 1:
        {
            block(@"one");
        }
            break;
        case 2:
        {
            block(@"one",@"two");
        }
            break;
        default:
            break;
    }
}

调用方式如下:

[self numbersOfArguments:2 block:^id(NSString *arg1,NSString *arg2){
        NSLog(@"%@  %@",arg1,arg2);
        return arg1;
    }];

这样我们通过指定参数的个数就可以获取多个参数的block的回调了.但这种方式很僵硬的地方在于需要指定参数个数,显得非常不灵活.如果要通过这种方式,达到RAC的效果也是很困难的,因为你无法确定绑定信号个数多少,所以不知道怎么传这个count参数.

利用invocation实现

看RAC的这种写法,我刚开始的想法是:通过自己构造一个block的结构体,将传入的block进行复制,再从这个复制的block中,拿到原block的方法签名(signature),然后拿到参数个数,从而来确定参数个数,貌似这样也能实现.但我去看RAC源码的时候,发现它用了更加巧妙的办法.

先写出我自己实现的方法:

- (void)bindConditions:(NSArray *)conditions bindBlock:(TBlock)block{
    if (conditions.count == 0) {
        return;
    }
    self.block = [block copy];

    id returnValue = [self invokeWithArguments:conditions];
}
  • conditions : 指传入的参数数组.
  • block : 指回调的block,这个block是没有参数的.

重点就在于这个invokeWithArguments方法.

- (id)invokeWithArguments:(NSArray *)conditions{
    // 这里拿到不定参数的方法
    SEL selector = [self selectorForArgumentCount:conditions.count];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
    invocation.selector = selector;
    
    for (NSInteger i = 0; i < conditions.count; i++) {
        id arg = conditions[i];
        NSInteger argIndex = i + 2;
        [invocation setArgument:&arg atIndex:argIndex];
    }
    [invocation invokeWithTarget:self];
    // 拿到返回值,__unsafe_unretained的作用是不立即释放
    __unsafe_unretained id returnVal;
    [invocation getReturnValue:&returnVal];
    return returnVal;
}

上面的代码其实很普通,很容易理解,唯一可能有点疑问的在于SEL selector = [self selectorForArgumentCount:conditions.count];这行代码,这就是RAC里比较巧妙的地方.这个方法内容是:

- (SEL)selectorForArgumentCount:(NSUInteger)count {
    NSCParameterAssert(count > 0);
    
    switch (count) {
        case 0: return NULL;
        case 1: return @selector(performWith:);
        case 2: return @selector(performWith::);
    }
    // 暂时只支持 2个参数
    NSCAssert(NO, @"The argument count is too damn high! Only blocks of up to 2 arguments are currently supported.");
    return NULL;
}

- (id)performWith:(id)obj1 {
    id (^block)(id) = self.block;
    return block(obj1);
}

- (id)performWith:(id)obj1 :(id)obj2 {
    id (^block)(id, id) = self.block;
    return block(obj1, obj2);
}

到这里,不知道大家看懂其中的巧妙之处没有.其实就是将block调用包装成了performWith方法,通过@selector(performWith::)这种方式确定了参数的个数,从而实现了不定参数的回调.这里RAC里是指定了最多存在15个参数,我这里只限定了2个.

这里将参数回调出去之后,我们就可以拿到这些参数在block中做一些逻辑处理了,而不用分散写到其他地方,不过这里并没有进行相关监听,所以并不能根据值改变来改变状态(待完成).另外,开头的RAC例子中,它的block是有返回值的,并且根据Button绑定的不同状态,返回了不同的值.例如enabled这个属性,返回的是NSNumber,backgroundColor返回的是UIColor类型.

在上面的invokeWithArguments方法中,其实我们已经拿到了方法的返回值,后面要解决的问题就是如何根据绑定的属性,返回对应的类型值,具体实现且听下回分解.

demo地址在此

你可能感兴趣的:([iOS][Block]block不定参数的回调方式)