获取当前方法调用的线程ID

时间:2009-10-24 00:23:27

标签: iphone objective-c cocoa multithreading

有没有办法打印当前执行当前方法的线程ID?

(objective-c please)

7 个答案:

答案 0 :(得分:214)

NSLog(@"%@", [NSThread currentThread]);

答案 1 :(得分:32)

#include <pthread.h>
...
mach_port_t machTID = pthread_mach_thread_np(pthread_self());
NSLog(@"current thread: %x", machTID);

答案 2 :(得分:20)

在Swift3中

print("Current thread \(Thread.current)")

答案 3 :(得分:11)

在Swift中

label.setBorder( new EmptyBorder(5, 5, 5, 5) );

答案 4 :(得分:0)

Swift4

print(“ \(Thread.current)”)

答案 5 :(得分:0)

NSLog 向控制台打印一个数字(在冒号后面的方括号中),标识调用它的线程。

NSLog output

答案 6 :(得分:-1)

你可以像这样破解一下(这只是印刷得很漂亮,但你可以继续分裂,直到你得到这个数字):

+ (NSString *)getPrettyCurrentThreadDescription {
    NSString *raw = [NSString stringWithFormat:@"%@", [NSThread currentThread]];

    NSArray *firstSplit = [raw componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{"]];
    if ([firstSplit count] > 1) {
        NSArray *secondSplit     = [firstSplit[1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"}"]];
        if ([secondSplit count] > 0) {
            NSString *numberAndName = secondSplit[0];
            return numberAndName;
        }
    }

    return raw;
}