NSInvocation 与策略模式

本文介绍了一种使用策略模式和NSInvocation实现事件响应的方法,通过一个字典保存不同事件对应的处理方法,从而简化了复杂事件处理过程中的代码结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值