iOS上的NSThread编号?

当你打印一个NSThread的描述,你会得到这样的东西:

<NSThread: 0x1e511b70>{name = (null), num = 1} 

这个“num”是否可用?

这只是为了debugging,所以不需要清除苹果的审批stream程。

这个数字实际上是NSThread的私人执行类中的一个ivar。 该类是_NSThreadInternal ,其名称是“_private”。 在那个对象里面,伊娃是seqNum

如果你愿意依靠无证的关键path,你可以直接拉它。 这将做到这一点(和良好的调用neilsbot使用valueForKeyPath而不是运行时调用):

 @implementation NSThread (GetSequenceNumber) - (NSInteger)sequenceNumber { return [[self valueForKeyPath:@"private.seqNum"] integerValue]; } @end 

我通过手动设置运行时调用ivar,然后NSLogging线程来testing它。 果然,描述反映了这种变化。 这显然没有logging,所以…

…使用风险自负。

这是一个有趣的练习,但事情通常是私人的原因。 发货的代码当然应该避免这样的事情,除非所有其他路线已经完全耗尽。

我继续写下@ xlc的build议,只是因为:

 @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:@"num" ] ) { return [ components[1] integerValue ] ; } } @throw @"couldn't get thread num"; return -1 ; } @end 

这就回答了从线程获取“num”的问题 – 虽然作为一个复制链接的问题可能有助于唯一标识线程的一般问题。

(我喜欢的答案是“生成一个UUID并放入线程的线程字典。)