怎么实现AFN中的常驻线程呢?

NSRunloop的底层实现其实是do-while在底层进行死循环。

方法一:

- (void)viewDidLoad {
    [super viewDidLoad];

     _thread = [[CXThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    
    [_thread start];

}
-(void)run{
    
    NSLog(@"run -- 旭宝爱吃鱼");
    //添加Port 实时监听
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    //添加runloop
    [[NSRunLoop currentRunLoop]run];
    
    
}
-(void)test{
    
    NSLog(@"test -- 旭宝爱吃鱼 %@",[NSThread currentThread]);
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    

//    让test方法在线程thread上实现
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    
}

方法二:

- (void)viewDidLoad {
    [super viewDidLoad];

     _thread = [[CXThread alloc]initWithTarget:self selector:@selector(run) object:nil];
    
    [_thread start];

}
-(void)run{
    
    NSLog(@"run -- 旭宝爱吃鱼");
    
    while (1) {
        //添加runloop
        [[NSRunLoop currentRunLoop]run];
    }
}
-(void)test{
    
    NSLog(@"test -- 旭宝爱吃鱼 %@",[NSThread currentThread]);
    
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    

//    让test方法在线程thread上实现
    [self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
    
}

你可能感兴趣的:(iOS开发,runloop)