2011-09-19 66 views
2

當我做PO [NSThread currentThread],我得到了PO [NSThread currentThread]

{名=(空),NUM = 4}

當我向左看我看到: enter image description here

看起來它的線程數6,不要4.還什麼性質做我們需要調用反正拿到該線程數?

[NSThread currentThread]。數?雖然不存在。

回答

6

線程數是沒有意義的,漂亮多了。

的線程實例,雖然是每個線程一個單例。巧合的是,您可以使用NSThread的地址。更好的是,仍然是傾聽mach_ * API並從該API中獲取線程ID。

[NSThread currentThread]大約是唯一一個數字作爲你會得到的。如果線程終止,然後創建一個新的線程,您可能會看到相同的地址出售。 mach機器人的API將銷售幾乎一樣獨特的東西,真的。

你想做什麼?

+0

你能否提供一些代碼?每個線程有一個單例? –

+0

如果你需要每個線程的數據,我想你想要的是' - [NSThread threadDictionary]',或者(在較低級別)''pthread_getspecific()''''pthread_setspecific()'。 –

+1

是的 - 如果你想要每個線程的數據,那就是要走的路。如果您試圖唯一標識一個線程,我可能會建議生成一個UUID並將其粘貼到線程的字典中。這樣,當一個線程退出並創建一個新線程時,就沒有碰撞的風險。 – bbum

-2

這是我貼到NSThread number on iOS?答案:


@implementation NSThread (ThreadGetIndex) 

-(NSInteger)getThreadNum 
{ 
    NSString * description = [ self description ] ; 
    NSArray * keyValuePairs = [ description componentsSeparatedByString:@"," ] ; 
    for(NSString * keyValuePair in keyValuePairs) 
    { 
     NSArray * components = [ keyValuePair componentsSeparatedByString:@"=" ] ; 
     NSString * key = components[0] ; 
     key = [ key stringByTrimmingCharactersInSet:[ NSCharacterSet whitespaceCharacterSet ] ] ; 
     if ([ key isEqualToString:@"number" ] || [ key isEqualToString:@"num" ]) 
     { 
      return [ components[1] integerValue ] ; 
     } 
    } 
    @throw @"couldn't get thread num"; 
    return -1 ; 
} 

@end 
+3

警告:在iOS8中,「num」已成爲「數字」(和「數字」和「名稱」已交換訂單...雖然上面的代碼很好) –

+0

無用的答案,這種方法只解析[ NSThread描述]並提取「數字」值,@Jim Thio的問題是完全不同的 – Kappe

+0

@DaveOwens謝謝,我改變了片段 – nielsbot