【问题标题】:How to pass a parameter by a @selector function in Objective C?如何通过Objective C中的@selector函数传递参数?
【发布时间】:2021-03-28 17:06:38
【问题描述】:
- (IBAction)alertShow:(NSButton *)sender {
    
    MHAlert* alert = [[MHAlert alloc]initWithMessageTitle:@"message" infoText:@"infoText" btnTitle:@"OK" target:self action:@selector(test:) secondBtnTitle:nil target:nil action:nil];
    [alert runModal];
}

- (void)test:(void(^)(BOOL isSuccess))handler
{
    if (handler) {
        handler(YES);
    }
    else
    {
        handler(NO);
    }
    
}

我想通过@selector(test:)传递一个参数,那就是块类型参数, 我检查了 test: 方法中的处理程序,当我按照代码显示进行操作时,发现它不是 not nil。 如果没有,我如何将 nil 值传递给 test: 方法。

我不想使用perform:方法,或者网上搜索后包装一个mew方法。

【问题讨论】:

  • 什么是MHAlert?它是否使用参数调用提供的选择器?您不能在 initWithMessageTitle 调用中传递参数; @selector 不是这样工作的。
  • 您可以使用NSInvocation。填写并致电invoke
  • 你能解释一下为什么你不想使用perform:withObject:吗?
  • 您可以将 block 参数转换为 id 并完全按照 @hacker_1989 所示的示例进行传递。

标签: ios objective-c macos cocoa cocoa-touch


【解决方案1】:

在initWithMessageTitle实现中使用带有参数的NSInvocation,并调用。

- (instancetype)initWithMessageTitle:(NSString *)message infoText:(NSString *)info btnTitle:(NSString *)title target:(id)target action:(SEL)action secondBtnTitle:(NSString *)secondTitle target:(id)secondTarget action:(SEL)secondAction
{
     NSMethodSignature *sig = [[target class] instanceMethodSignatureForSelector:action];
     NSInvocation* invoc = [NSInvocation invocationWithMethodSignature:sig];
     //[invoc setArgument: atIndex:2];
     invoc.selector = action;
     [invoc invokeWithTarget:target];
}

填写并调用受 Cy-4AH 启发的调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多