Blu*_*hin 57 objective-c selector
我有一个SEL从当前对象获取的代码示例,
SEL callback = @selector(mymethod:parameter2);
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的方法
-(void)mymethod:(id)v1 parameter2;(NSString*)v2 {
}
Run Code Online (Sandbox Code Playgroud)
现在我需要转移mymethod到另一个对象,比如说myDelegate.
我试过了:
SEL callback = @selector(myDelegate, mymethod:parameter2);
Run Code Online (Sandbox Code Playgroud)
但它不会编译.
Jas*_*oco 100
SEL是一种表示Objective-C中的选择器的类型.@selector()关键字返回您描述的SEL.它不是函数指针,您不能将任何对象或引用传递给它.对于选择器(方法)中的每个变量,您必须在对@selector的调用中表示该变量.例如:
-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
Run Code Online (Sandbox Code Playgroud)
选择器通常传递给委托方法和回调,以指定在回调期间应在特定对象上调用哪个方法.例如,在创建计时器时,回调方法具体定义为:
-(void)someMethod:(NSTimer*)timer;
Run Code Online (Sandbox Code Playgroud)
因此,当您安排计时器时,您将使用@selector指定对象上的哪个方法实际上将负责回调:
@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您指定每隔30秒使用myTimerCallback向对象obj发送消息.
Gra*_*erg 18
您无法在@selector()中传递参数.
看起来你正在尝试实现回调.最好的方法是这样的:
[object setCallbackObject:self withSelector:@selector(myMethod:)];
Run Code Online (Sandbox Code Playgroud)
然后在你的对象的setCallbackObject:withSelector:方法:你可以调用你的回调方法.
-(void)setCallbackObject:(id)anObject withSelector:(SEL)selector {
[anObject performSelector:selector];
}
Run Code Online (Sandbox Code Playgroud)
除了已经有关选择器的说法之外,您可能希望查看NSInvocation类.
NSInvocation是一个静态呈现的Objective-C消息,也就是说,它是一个变成对象的动作.NSInvocation对象主要通过NSTimer对象和分布式对象系统用于在对象之间和应用程序之间存储和转发消息.
NSInvocation对象包含Objective-C消息的所有元素:目标,选择器,参数和返回值.可以直接设置这些元素中的每一个,并在调度NSInvocation对象时自动设置返回值.
请记住,虽然它在某些情况下很有用,但您不能在正常的编码日使用NSInvocation.如果您只是想让两个对象相互通信,请考虑定义一个非正式或正式的委托协议,或者如已经提到的那样传递一个选择器和目标对象.