【问题标题】:getting the object passed to the NSThread selector获取传递给 NSThread 选择器的对象
【发布时间】:2011-03-15 10:24:51
【问题描述】:

当我创建一个 NSThread 时,我向它传递了一个我希望进程知道的数字。我可以理解如何设置数字,但我不知道如何从线程选择器方法中读取数字,以便我可以将其传递给计时器。

你是怎么做到的?

-(void) setthread
{ 

//这里把数字传给选择器就好了

NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:[NSNumber numberWithInt:index]];/
    [timerThread setThreadPriority:0.5];
    [timerThread start]; //start the thread 

}

// 不知道如何读取传递给这个选择器的值

-(void) startTimerThread
{


    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
    [[NSTimer scheduledTimerWithTimeInterval: 0.1
                                      target: self
                                    selector: @selector(timerTick:)
                                    userInfo: thenumberhere
                                     repeats: YES] retain];

    [runLoop run];
    [pool release];
}

- (void)timerTick:(NSTimer *)timer
{
    //code
}

【问题讨论】:

    标签: iphone cocoa ios4 nsthread


    【解决方案1】:

    您指定的选择器错误:

    @selector(startTimerThread)   // we are missing ':' at the end
    

    最后应该有:,像这样:

    @selector(startTimerThread:) 
    

    这表明它是一个接受一个参数的选择器。

    然后在你的startTimerThread方法中传入参数:

    -(void) startTimerThread:(NSNumber *)myNumber {
        // ... etc
    

    【讨论】:

    • 这个答案只是帮助我解决了类似的问题。 +1 ;)
    【解决方案2】:

    那行不通.. 这将:

    NSThread* timerThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread:) object:[NSNumber numberWithInt:index]];
    
    
    -(void) startTimerThread:(NSNumber *)thenumberhere
    {
    
    
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
        [[NSTimer scheduledTimerWithTimeInterval: 0.1
                                          target: self
                                        selector: @selector(timerTick:)
                                        userInfo: thenumberhere
                                         repeats: YES] retain];
    
        [runLoop run];
        [pool release];
    }
    

    您“忘记”将与选择器一起作为参数传递的对象添加到您实现的方法中。

    【讨论】:

    • 为什么要使用NSRunLoop??
    • 一年多以前,我改编了问题中给出的代码。询问配音。
    猜你喜欢
    • 2013-03-23
    • 2021-04-28
    • 2018-03-04
    • 2012-03-20
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多