NSInvocation 与策略模式

来源:互联网 发布:spark 提交python脚本 编辑:程序博客网 时间:2024/06/18 13:26
- (NSDictionary <NSString *, NSInvocation *> *)eventStrategy{    if (_eventStrategy == nil) {        _eventStrategy = @{                           @"kBLGoodsDetailTicketEvent":[self createInvocationWithSelector:@selector(ticketEvent:)],                           @"kBLGoodsDetailPromotionEvent":[self createInvocationWithSelector:@selector(myLog:)],                           };    }    return _eventStrategy;}- (void)ticketEvent:(NSDictionary *)userInfo{    NSLog(@"%@ticketEvent",userInfo);}- (NSDictionary *)myLog:(NSDictionary *)userInfo{    NSLog(@"%@ticketEvent",userInfo);    return userInfo;}#pragma mark - event response- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{    NSLog(@"%@",eventName);    NSInvocation * invocatin = self.eventStrategy[@"kBLGoodsDetailTicketEvent"];    [invocatin setArgument:&userInfo atIndex:2];    [invocatin invoke];    // 如果需要让事件继续往上传递,则调用下面的语句    // [super routerEventWithName:eventName userInfo:userInfo];}- (NSInvocation *)createInvocationWithSelector:(SEL)myMethod2 {    NSMethodSignature * sig  = [[self class] instanceMethodSignatureForSelector:myMethod2];//有参数的时候    NSInvocation * invocatin = [NSInvocation invocationWithMethodSignature:sig];    [invocatin setTarget:self];    [invocatin setSelector:myMethod2];    return invocatin;}

直接贴代码
当有点击事件的时候
会发给routerEventWithName 方法
按照多个事件回传的时候,
可能要根据点击事件处理不同的方法
需要写大量的if else
避免 这种方式 就是策略模式
一个字典 保存所有的方法
回传根据方法名称 来决定 调用哪个方法
NSInvocation 做了中转处理

关键代码是[invocatin setArgument:&userInfo atIndex:2];

就是把userinfo 赋值给 第二个参数

如果要增加参数 就再后面付给 第3 个 第 4 个 就完成了
‘[invocatin setArgument:&userInfo atIndex:3];`