代码之家  ›  专栏  ›  技术社区  ›  Georg Schölly Crazy Developer

如何将本机C类型与performSelectorOnMainThread:一起使用?

  •  3
  • Georg Schölly Crazy Developer  · 技术社区  · 16 年前

    (void)setDoubleValue:(double)value performSelectorOnMainThread: .

    我认为有效的方法是:

    NSNumber *progress = [NSNumber numberWithDouble:50.0];
    [progressIndicator performSelectorOnMainThread:@selector(setDoubleValue:)
                                        withObject:progress
                                     waitUntilDone:NO];
    

    没用。

    - (void)updateProgressIndicator:(NSNumber *)progress
    {
        [progressIndicator setDoubleValue:[progress doubleValue]];
    }
    

    可以,但不是很干净。

    NSInvocation .

    NSInvocation *setDoubleInvocation;;
    SEL selector = @selector(setDoubleValue:);
    NSMethodSignature *signature;
    signature = [progressIndicator methodSignatureForSelector:selector];
    setDoubleInvocation = [NSInvocation invocationWithMethodSignature:signature];
    [setDoubleInvocation setSelector:selector];
    [setDoubleInvocation setTarget:progressIndicator];
    
    double progress = 50.0;
    [setDoubleInvocation setArgument:&progress atIndex:2];
    
    [setDoubleInvocation performSelectorOnMainThread:@selector(invoke)
                                          withObject:nil
                                       waitUntilDone:NO];
    

    这个解决方案是可行的,但它使用了大量代码,而且速度非常慢。(即使我存储了调用。)

    还有别的办法吗?

    4 回复  |  直到 15 年前
        1
  •  9
  •   bbum    16 年前

    如果您在雪豹上,可以使用块:

    dispatch_async(dispatch_get_main_queue(), ^{
        [progressIndicator setDoubleValue: 50.0];
    });
    
        2
  •  7
  •   Georg Schölly Crazy Developer    16 年前

    您需要编写一个自定义的取消装箱方法来包装setDoubleValue:。

    - (void) setDoubleValueAsNumber: (NSNumber *) number {
       [self setDoubleValue: [number doubleValue]];
    }
    

        3
  •  2
  •   Brad Larson    16 年前

    戴夫·德里宾有一个 solution for this 其形状为NSObject上的类别。他的类别将方法调用包装在NSInvocation中,并在主线程上调用该方法。这样,您可以使用您喜欢的任何方法接口,包括参数的基本类型。

    这个 Amber framework

        4
  •  -2
  •   Jim Witte    15 年前

    此博客帖子: http://www.cimgf.com/2008/03/01/does-objective-c-perform-autoboxing-on-primitives/ 指出,虽然Cocoa不会自动装箱原语,但它会自动取消装箱。因此,数字和布尔值至少可以作为NSNumber类传入,并且被调用的函数将自动取消装箱。我一直在使用一个代理对象(Uli的UKMainThreadProxy*),它工作得很好,尽管我确信它和其他任何东西一样有局限性。