常驻线程

- (void)viewDidLoad {
    [super viewDidLoad];

    self.thread = [[XMGThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [self.thread start];
}
/**
 * 这种方式虽然能保住线程的名,但是这条线程就无法处理其他行为(事件)
 */
- (void)run
{
    NSLog(@"----------run----%@", [NSThread currentThread]);

    while (1); // 当前线程永远在处理这行代码

    NSLog(@"---------");
}
//不推荐这种做法 虽然能实现想要的效果但是代码
flag = 1
- (void)run
{
    NSLog(@"----------run----%@", [NSThread currentThread]);

    while (flag) {
        [[NSRunLoop currentRunLoop] run];
        NSLog(@"----4444-----"); //线程会一直执行这段代码 直到有事情添加到NSRunLoop中
    }

    NSLog(@"---------");
}

//关闭线程
//测试:并没有用
- (IBAction)btn:(id)sender {

    flag = 0;

}
//推荐做法 给RunLoop添加事件
- (void)run
{
    NSLog(@"----------run----%@", [NSThread currentThread]);

    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];

    NSLog(@"---------");
}

//关闭线程
//不推荐做法
- (IBAction)btn:(id)sender {

    [self performSelector:@selector(test1) onThread:self.thread withObject:nil waitUntilDone:NO];

}

-(void)test1{
    [NSThread exit];
}

//不一定是最好的做法
- (IBAction)btn:(id)sender {

    [self performSelector:@selector(stop) onThread:self.thread withObject:nil waitUntilDone:NO];
}

- (void)stop
{
    [self performSelector:@selector(_stop) onThread:_thread withObject:nil waitUntilDone:NO];
    _thread = nil;
}

- (void)_stop
{
    CFRunLoopStop(CFRunLoopGetCurrent());
}

//好方法记得百度
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}

- (void)test
{
    NSLog(@"----------test----%@", [NSThread currentThread]);
}

results matching ""

    No results matching ""