如何将@selector作为参数传递?

ero*_*ppa 51 iphone objective-c selector

对于方法:

[NSThread detachNewThreadSelector:@selector(method:) toTarget:self withObject:(id)SELECTOR];
Run Code Online (Sandbox Code Playgroud)

如何传入@selector?我尝试将它转换为(id)以使其编译,但它在运行时崩溃.


更具体地说,我有一个像这样的方法:

+(void)method1:(SEL)selector{
[NSThread detachNewThreadSelector:@selector(method2:) toTarget:self withObject:selector];   
}
Run Code Online (Sandbox Code Playgroud)

它崩溃了.如何在不崩溃的情况下传入选择器,以便新线程可以在线程准备好时调用选择器?

Chu*_*uck 67

这里的问题不是将选择器传递给方法本身,而是将选择器传递给期望对象.要将非对象值作为对象传递,可以使用NSValue.在这种情况下,您需要创建一个接受NSValue并检索适当选择器的方法.这是一个示例实现:

@implementation Thing
- (void)method:(SEL)selector {
    // Do something
}

- (void)methodWithSelectorValue:(NSValue *)value {
    SEL selector;

    // Guard against buffer overflow
    if (strcmp([value objCType], @encode(SEL)) == 0) {
        [value getValue:&selector];
        [self method:selector];
    }
}

- (void)otherMethodShownInYourExample {
    SEL selector = @selector(something);
    NSValue *selectorAsValue = [NSValue valueWithBytes:&selector objCType:@encode(SEL)];
    [NSThread detachNewThreadSelector:@selector(methodWithSelectorValue:) toTarget:self withObject:selectorAsValue];
}
@end
Run Code Online (Sandbox Code Playgroud)

  • @cstack:如果你看一下这个问题,那么产生一个新线程就是他正在尝试做的事情.所以我在我的例子中使用了相同的任务.但是这种技术并不特定于产生新线程. (2认同)

use*_*008 42

您可以使用NSStringFromSelector()NSSelectorFromString()函数在选择器和字符串对象之间进行转换.所以你可以只传递字符串对象.

或者,如果您不想更改方法,可以创建一个NSInvocation为方法调用创建调用(因为它可以使用非对象参数设置调用),然后调用它[NSThread detachNewThreadSelector:@selector(invoke) toTarget:myInvocation withObject:nil];