When you print a NSThread's description, you get something like this:
<NSThread: 0x1e511b70>{name = (null), num = 1}
Is this "num" available somehow?
This is for debugging only, so it does not need to clear Apple's approval process.
That number is actually an ivar in NSThread's private implementation class. The class is _NSThreadInternal
, and its name is "_private". Inside that object, the ivar is seqNum
.
You can pull it directly if you're willing to rely on undocumented key paths. This'll do it (and good call neilsbot on using valueForKeyPath instead of runtime calls):
@implementation NSThread (GetSequenceNumber)
- (NSInteger)sequenceNumber
{
return [[self valueForKeyPath:@"private.seqNum"] integerValue];
}
@end
I tested it by manually setting that ivar with runtime calls and then NSLogging the thread. Sure enough, the description reflected the change. This is obviously not documented, so...
It's a fun exercise, but things are typically private for a reason. Shipped code should certainly avoid things like this unless all other routes have been thoroughly exhausted.
I went ahead and wrote out @xlc's suggestion, just because:
@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
This answers the question of getting "num" from the thread--although the question linked as a dupe might be helpful for the general question of uniquely identifying threads.
(The answer I like there is "generate a UUID and put in in the thread's thread dictionary.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With