@selector - 有多个参数?

fuz*_*oat 27 objective-c

@selector今天第一次使用,并且无法弄清楚如何做以下事情?@selector如果你有一个以上的论点,你会怎么写?

没有参数:

-(void)printText {
    NSLog(@"Fish");
}

[self performSelector:@selector(printText) withObject:nil afterDelay:0.25];
Run Code Online (Sandbox Code Playgroud)

单一论点:

-(void)printText:(NSString *)myText {
    NSLog(@"Text = %@", myText);
}

[self performSelector:@selector(printText:) withObject:@"Cake" afterDelay:0.25];
Run Code Online (Sandbox Code Playgroud)

两个论点:

-(void)printText:(NSString *)myText andMore:(NSString *)extraText {
    NSLog(@"Text = %@ and %@", myText, extraText);
}

[self performSelector:@selector(printText:andMore:) withObject:@"Cake" withObject:@"Chips"];
Run Code Online (Sandbox Code Playgroud)

多个参数:(即超过2个)

NSInvocation

cob*_*bal 38

 

 - (id)performSelector:(SEL)aSelector
           withObject:(id)anObject  
           withObject:(id)anotherObject
Run Code Online (Sandbox Code Playgroud)

文档:

此方法与performSelector相同:除了可以为aSelector提供两个参数.aSelector应该标识一个可以采用id类型的两个参数的方法.对于具有其他参数类型和返回值的方法,请使用NSInvocation.

所以在你的情况下你会使用:

[self performSelector:@selector(printText:andMore:)
           withObject:@"Cake"
           withObject:@"More Cake"]
Run Code Online (Sandbox Code Playgroud)


Ben*_*Uri 17

当您有两个以上的参数时,作为NSInvocation的替代方法,您可以使用NSObject的-methodForSelector:如下例所示:

SEL a_selector = ...
Type1 obj1 = ...
Type2 obj2 = ...
Type3 obj3 = ...
typedef void (*MethodType)(id, SEL, Type1, Type2, Type3);
MethodType methodToCall;
methodToCall = (MethodType)[target methodForSelector:a_selector];
methodToCall(target, a_selector, obj1, obj_of_type2, obj_of_type3);
Run Code Online (Sandbox Code Playgroud)


aqu*_*qua 14

我有一个问题,我需要使用afterDelay带有多个参数的@selector方法.解?使用包装函数!

说这是我传递给的函数@selector:

-(void)myFunct:(NSString *)arg1 andArg:(NSString *)arg2 andYetAnotherArg:(NSString *)arg3;
Run Code Online (Sandbox Code Playgroud)

显然,我甚至不能withObject: withObject:在这里使用,所以,做一个包装!

-(void)myFunctWrapper:(NSArray *)myArgs {
    [self myFunct:[myArgs objectAtIndex:0] andArg:[myArgs objectAtIndex:1] andYetAnotherArg:[myArgs objectAtIndex:2]];
}
Run Code Online (Sandbox Code Playgroud)

通过这样做来使用它:

NSArray *argArray = [NSArray arrayWithObjects:string1,string2,string3,nil];
[self performSelector:@selector(myFunctWrapper:) withObject:argArray afterDelay:1.0];
Run Code Online (Sandbox Code Playgroud)

这样我可以有多个参数使用带有延迟的选择器.


ken*_*ytm 5

@selector(printText:andMore:)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,但我如何指定@"Cake"和@"More Cake"的参数? (4认同)