Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSThread number on iOS? [duplicate]

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.

like image 632
Steven Fisher Avatar asked Mar 21 '13 21:03

Steven Fisher


2 Answers

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...

...use at your own risk.

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.

like image 85
Matt Wilding Avatar answered Nov 19 '22 21:11

Matt Wilding


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.)

like image 7
nielsbot Avatar answered Nov 19 '22 22:11

nielsbot