2011-03-15 34 views
0

當我創建一個NSThread時,我將它傳遞給一個我希望進程知道的數字。我可以理解如何設置數字,但我不知道如何從線程選擇器方法讀取數字,以便我可以將它傳遞給定時器。獲取傳遞給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 
} 

回答

4

您指定的是選擇錯了:

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

它應該在年底有:,就像這樣:

@selector(startTimerThread:) 

這表明它是一個選擇這需要一個參數。

然後採取在參數在startTimerThread方法:

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

這個答案只是幫助我解決了類似的問題。 +1;) – craig1231 2013-05-31 18:43:04

0

這是行不通的.. 這將:

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]; 
} 
'

你'忘記'添加對象,你將選擇器作爲參數傳遞給你實現的方法。

+0

爲什麼要使用NSRunLoop? – IKKA 2013-08-01 11:27:21

+0

我在一年多前修改了這個問題的代碼。詢問配音。 – Jake 2013-08-02 14:24:47