Runloop开启常驻线程

2020-05-18  本文已影响0人  Lee_Jo
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) NSThread *thread;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 400, 330, 34);
    [button addTarget:self action:@selector(click:)
     forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor grayColor];
    [self.view addSubview:button];
    self.thread = [[NSThread alloc] initWithTarget:self
                                          selector:@selector(excute:)
                                            object:nil];
    [self.thread start];
}

- (void)excute:(id)sender {
    @autoreleasepool {
        NSRunLoop *loop = [NSRunLoop currentRunLoop];
        [loop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
        [loop run];
    }
}

- (void)click:(id)sender {
    [self performSelector:@selector(excute:)
                 onThread:self.thread
               withObject:nil
            waitUntilDone:NO];
}

@end
上一篇下一篇

猜你喜欢

热点阅读