NSThread number on iOS? [duplicate]

余生颓废 提交于 2019-12-29 07:33:08

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/15558411/nsthread-number-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!