NSThread 通过 NSRunLoop 完成单线程循环

Test.m

创建独立的 thread:

+ (void)testThreadMain {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"test"];
        
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

// 独立线程
+ (NSThread *)testThread {
    static NSThread *testThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        testThread = [[NSThread alloc] initWithTarget:self selector:@selector(testThreadMain) object:nil];
        [testThread start];
    });
    
    return testThread;
}

线程跳转:

- (void)log {
    NSLog(@"current thread: %@", [NSThread currentThread]);
}

// 线程切换,在 main thread 中调用这个方法,切换至 testThread
- (void)test {
    [self performSelector:@selector(log) onThread:[[self class] testThread] withObject:nil waitUntilDone:NO];
}

main.m

循环调用:

#import 
#import "Test.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        for (int i = 0; i < 100; i++) {
            [[[Test alloc] init] test];
        }
        
        [NSThread sleepForTimeInterval:100];
    }
    return 0;
}

结果

打印日志:

...
2016-03-25 15:22:24.270 RunLoopTest[2436:217874] current thread: {number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: {number = 2, name = test}
2016-03-25 15:22:24.271 RunLoopTest[2436:217874] current thread: {number = 2, name = test}
...

参考

深入理解RunLoop

你可能感兴趣的:(NSThread 通过 NSRunLoop 完成单线程循环)