NSThread

NSThread相对于gcd和nsoperation来说偏向于底层,有时候会用到它的一些方法,比如长时间等待一个线程,或者频繁使用的时候

  [NSThread sleepForTimeInterval:2];//让线程睡两秒
    [NSThread sleepUntilDate:[NSDate date]];//让线程睡到指定的日期点
    //用NSThread新建子线程
    [NSThread detachNewThreadSelector:@selector(go) toTarget:self withObject:nil];


-(void)go
{
    NSLog(@"%@",[NSThread currentThread]);
    NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/pic/item/9922720e0cf3d7ca60432a7df41fbe096b63a907.jpg"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        _imageback2.image = [UIImage imageWithData:data];
    });
}

 Runloop的使用:

 工作的特点:

    1> 当有事件发生时,Runloop会根据具体的事件类型通知应用程序作出响应;

    2> 当没有事件发生时,Runloop会进入休眠状态,从而达到省电的目的;

    3> 当事件再次发生时,Runloop会被重新唤醒,处理事件。

    注意:一般在开发中很少会主动创建Runloop,而通常会把事件添加到Runloop中。

//添加一个时间runloop
    NSRunLoop *loop = [NSRunLoop currentRunLoop];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(go) userInfo:nil repeats:YES];
    [loop addTimer:timer forMode:NSDefaultRunLoopMode];

 

原文地址:https://www.cnblogs.com/moxuexiaotong/p/4968629.html