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)
use*_*008 42
您可以使用NSStringFromSelector()和NSSelectorFromString()函数在选择器和字符串对象之间进行转换.所以你可以只传递字符串对象.
或者,如果您不想更改方法,可以创建一个NSInvocation为方法调用创建调用(因为它可以使用非对象参数设置调用),然后调用它[NSThread detachNewThreadSelector:@selector(invoke) toTarget:myInvocation withObject:nil];
| 归档时间: |
|
| 查看次数: |
43242 次 |
| 最近记录: |