ReactiveCocoa 学习笔记八(RACBlockTrampoline)

RACBlockTrampoline

RACBlockTrampoline 类是 ReactiveCocoa 框架中内部使用的类,用于调用动态的回调代码块。

+ (id)invokeBlock:(id)block withArguments:(RACTuple *)arguments {
	NSCParameterAssert(block != NULL);

	RACBlockTrampoline *trampoline = [[self alloc] initWithBlock:block];
	return [trampoline invokeWithArguments:arguments];
}

要正常使用该方法,block 不能为空,并且其所包含的参数必须和 arguments 的分量个数保持一致,且参数是必须的,当然最多支持 15 个参数。

- (id)invokeWithArguments:(RACTuple *)arguments {
	SEL selector = [self selectorForArgumentCount:arguments.count];
	NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
	invocation.selector = selector;
	invocation.target = self;

	for (NSUInteger i = 0; i < arguments.count; i++) {
		id arg = arguments[i];
		NSInteger argIndex = (NSInteger)(i + 2);
		[invocation setArgument:&arg atIndex:argIndex];
	}

	[invocation invoke];
	
	__unsafe_unretained id returnVal;
	[invocation getReturnValue:&returnVal];
	return returnVal;
}

这个方法很简单,首先调用下面的方法,根据 arguments 所包含的分量个数确定 block 中的参数个数,从而确定后面需要调用的方法。

- (SEL)selectorForArgumentCount:(NSUInteger)count {
	NSCParameterAssert(count > 0);

	switch (count) {
		case 0: return NULL;
		case 1: return @selector(performWith:);
		case 2: return @selector(performWith::);
		···	 //省略
		case 15: return @selector(performWith:::::::::::::::);
	}
	NSCAssert(NO, @"The argument count is too damn high! Only blocks of up to 15 arguments are currently supported.");
	return NULL		
}

根据返回的 SEL 变量创建一个 NSInvocation 实例,而后绑定参数,最后调用 invoke 方法。


如果要在框架外使用该类,需要导入 RACBlockTrampoline.h 头文件。

#import "RACBlockTrampoline.h"

- (void)test {
    id (^block)(id obj) = ^ id (id obj) {
        NSLog(@"block is executed : %@ .",obj);
        return obj;
    };
    
    id obj = [RACBlockTrampoline invokeBlock:block withArguments:RACTuplePack(@100)];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值