NSInvocation 与策略模式

- (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];`

猜你喜欢

转载自blog.csdn.net/github_35041937/article/details/78226056