对于方法:

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

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


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

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

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

推荐答案

这里的问题不是将 Select 器传递给方法本身,而是在需要对象的位置传递 Select 器.要将非对象值作为对象传递,可以使用NSValue.在这种情况下,需要创建一个接受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

Objective-c相关问答推荐

应用程序终止时处理推送通知

通过指针算术访问数组值与 C 中的下标

具有自定义视图的相机

在objective-c中isa是什么意思?

为什么 UITableViewCell Select 时所有背景都消失了?

NSFileManager 唯一的文件名

更改 UINavigationBar 字体属性?

iOS7过度导航栏按钮填充

Objective C 静态类变量

判断 NSString 是否只是由空格组成

当表格重新出现时,UITableView 不会自动取消 Select 选定的行

如何在 Objective-C 中创建一个空白的透明 png?

如何从输入 IB 的 UILabel 文本中插入新行 \n?

自定义导航栏样式 - iOS

如何检测 NSString 是否为空?

嵌入自定义容器视图控制器时,内容位于导航栏下方.

Core Text在iOS中计算字母框架

为整个 iPhone / iPad 应用程序设置背景图像

为什么我们不能在当前队列上使用 dispatch_sync?

如何根据按钮按下重新加载/刷新 UIPickerView(带有新数据数组)?