如何将@selector作为parameter passing?

对于该方法:

[NSThread detachNewThreadSelector:@selector(method:) toTarget:self withObject:(id)SELECTOR]; 

我如何通过@select器? 我试图将其转换为(id)使其编译,但它在运行时崩溃。


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

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

它崩溃。 如何在不崩溃的情况下传递select器,以便在线程准备就绪时新线程可以调用select器?

这里的问题不是将select器传递给方法,而是将select器传递到期望的对象。 要将非对象值作为对象传递,可以使用NSValue 。 在这种情况下,你需要创build一个方法来接受一个NSValue并且获取适当的select器。 这是一个示例实现:

 @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 

您可以使用NSStringFromSelector()NSSelectorFromString()函数在select器和string对象之间进行转换。 所以你可以传递string对象。

另外,如果你不想改变你的方法,你可以创build一个NSInvocation为你的方法调用创build一个调用(因为它可以设置非对象参数的调用),然后调用它[NSThread detachNewThreadSelector:@selector(invoke) toTarget:myInvocation withObject:nil];

使用NSValue,如下所示:

 +(void)method1:(SEL)selector { NSValue *selectorValue = [NSValue value:&selector withObjCType:@encode(SEL)]; [NSThread detachNewThreadSelector:@selector(method2:) toTarget:self withObject:selectorValue]; } 

NSValue旨在作为任意非对象types的对象包装器。

请参阅: 传递方法作为参数

如果你不想指定一个对象,只需使用nil。

 [NSThread detachNewThreadSelector:@selector(method:) toTarget:self withObject:nil]; 

如果你需要传递一个对象给select器,它会看起来像这样。

在这里,我将一个string传递给“setText”方法。

 NSString *string = @"hello world!"; [NSThread detachNewThreadSelector:@selector(setText:) toTarget:self withObject:string]; -(void)setText:(NSString *)string { [UITextField setText:string]; }