代码之家  ›  专栏  ›  技术社区  ›  erotsppa

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

  •  51
  • erotsppa  · 技术社区  · 16 年前

    对于该方法:

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

    如何传入@选择器?我尝试将其强制转换为(id)以使其编译,但它在运行时崩溃。


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

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

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

    5 回复  |  直到 12 年前
        1
  •  67
  •   Chuck    14 年前

    这里的问题不是将选择器本身传递给方法,而是传递一个需要对象的选择器。要将非对象值作为对象传递,可以使用 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
    
        2
  •  42
  •   user102008    14 年前

    您可以使用 NSStringFromSelector() NSSelectorFromString() 功能。所以您可以只传递字符串对象。

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

        3
  •  4
  •   BJ Homer    15 年前

    使用nsvalue,如下所示:

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

    nsvalue用作任意非对象类型的对象包装器。

        4
  •  2
  •   Community CDub    8 年前
        5
  •  0
  •   Brandon Schlenker    16 年前

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

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

    如果需要将一个对象传递给选择器,它将看起来像这样。

    这里我将向方法“settext”传递一个字符串。

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