简体   繁体   English

如何将 arguments 添加到作为 ObjectiveC 中的参数传递的选择器

[英]How can I add arguments to a selector passed as a parameter in ObjectiveC

I'm trying to write a method in Objective C which takes a @selector as a parameter.我正在尝试在 Objective C 中编写一个方法,该方法将 @selector 作为参数。 It works fine - provided that I don't want the selector itself to have parameters (and I do).它工作正常 - 前提是我不希望选择器本身有参数(我有)。

- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
    NSLog(@"%@ %@", testString1, testString2);
}

- (void)executeSelector:(SEL)func fromObject:(id)object {
    [object performSelector:func];
}

- (void)runSelector {
    NSString* string1 = @"Hello ";
    NSString* string2 = @"World";
    [self executeSelector:@selector(testWithInput:andInput:) fromObject:self];
}

But how, in the runSelector function can I specify that string1 and string2 need to be passed in as arguments for the selector?但是,如何在 runSelector function 中指定 string1 和 string2 需要作为选择器传入 arguments 呢?

I suppose that I could pass in the parameters as a separate set of arguments to execute selector - but that feels quite messy.我想我可以将参数作为一组单独的 arguments 传递给执行选择器——但这感觉很乱。 Is there a neater way?有没有更简洁的方法?

I've done a bit of research, on StackOverflow (and elsewhere) - but either the answer isn't quite right or I can't understand it fully.我在 StackOverflow(和其他地方)上做了一些研究——但要么答案不太正确,要么我不能完全理解。

How to I pass @selector as a parameter? 如何将@selector 作为参数传递?

How can I pass a parameter to a selector? 如何将参数传递给选择器?

Objective-C: Calling selectors with multiple arguments Objective-C:使用多个 arguments 调用选择器

In fact, I'm comfortable passing parameters to selectors normally - it's when the selector is itself a parameter that I have a problem.实际上,我很舒服地将参数传递给选择器 - 选择器本身就是一个我有问题的参数。

You need to add parameters for the arguments. Your contrived example will work with the following changes:您需要为 arguments 添加参数。您设计的示例将适用于以下更改:

- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
    NSLog(@"%@ %@", testString1, testString2);
}

- (void)executeSelector:(SEL)func fromObject:(id)object withString1:(NSString *)string1 andString2:(NSString *)string2 {
    // This doesn't scale. Two arguments is as far as you can go using `performSelector`.
    [object performSelector:func withObject:string1 withObject:string2];
}

- (void)runSelector {
    NSString* string1 = @"Hello ";
    NSString* string2 = @"World";
    [self executeSelector:@selector(testWithInput:andInput:) fromObject:self withString1:string1 andString2:string2];
}

Since it's unclear what you are actually trying to accomplish it is difficult to offer any further advice on a better solution other than to suggest using blocks is likely a better choice.由于不清楚您实际要完成什么,因此除了建议使用块可能是更好的选择之外,很难就更好的解决方案提供任何进一步的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM