DukeDu
DukeDu

Reputation: 91

How to pass a parameter by a @selector function in Objective C?

- (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);
    }
    
}

I want to pass a parameter by @selector(test:), and that is a block type parameter, I check the handler in test: method, and find it was not nil, when I do as code show. if not, how can I pass a nil value to test: method.

I don't want to use perform: method, or wrap a mew method after searching on net.

Upvotes: 1

Views: 431

Answers (1)

DukeDu
DukeDu

Reputation: 91

Use NSInvocation inited with parameter in the initWithMessageTitle implementation, and invoke.

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

Fill it and call invoke inspired by Cy-4AH.

Upvotes: 2

Related Questions