如何将@selector作为参数传递? [英] How to I pass @selector as a parameter?
问题描述
对于方法:
[NSThread detachNewThreadSelector:@selector(method:) toTarget:self withObject:(id)SELECTOR];
如何传入@selector?我尝试将它转换为(id)以使其编译,但它在运行时崩溃。
How do I pass in a @selector? I tried casting it to (id) to make it compile, but it crashes in runtime.
更具体地说,我有这样的方法:
More specifically, I have a method like this:
+(void)method1:(SEL)selector{
[NSThread detachNewThreadSelector:@selector(method2:) toTarget:self withObject:selector];
}
它崩溃了。如何在没有崩溃的情况下传入选择器,以便新线程可以在线程就绪时调用选择器?
It crashes. How do I pass in the selector without crashing, so that the new thread can call the selector when the thread is ready?
推荐答案
这里的问题不是将选择器传递给方法本身,而是将选择器传递给期望对象。要将非对象值作为对象传递,可以使用 NSValue
。在这种情况下,您需要创建一个接受NSValue并检索适当选择器的方法。这是一个示例实现:
The problem here isn't passing a selector to a method, per se, but passing a selector where an object is expected. To pass a non-object value as an object, you can use NSValue
. In this case, you'll need to create a method that accepts an NSValue and retrieves the appropriate selector. Here's an example implementation:
@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
这篇关于如何将@selector作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!