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.
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.
valueForKeyPath:
work here? –
Inflate 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.)
objc_setAssociatedObject()
/objc_getAssociatedObject()
–
Inflate © 2022 - 2024 — McMap. All rights reserved.
-[<thread> threadDictionary]
? (You can store thread-local information inNSThread
's threadDictionary...) – Inflate+[NSThread alloc]
to keep track of the number of threads created... (then retrieve this information via a category onNSThread
) – Inflate[thread description]
and extract the number from it – Methuselah[thread description]
– Inflate0x1e511b70
that's highlighted in red (I wonder what language SO thought that line was in), not thenum
key in the dictionary. Sorry. – Moselle