天天看点

iOS开发—线程的模拟暂停和继续操作

表视图开启线程下载远程的网络界面,滚动页面时势必会有影响,降低用户的体验。针对这种情况,当用户滚动屏幕的时候,暂停队列;用户停止滚动的时候,继续恢复队列。接下来通过一个案例,演示如何暂停和继续操作,具体内容如下:

(1)新建一个SingleViewApplication工程,命名为“13-SuspendAndContinue”;

(2)进入Main.StoryBoard,从对象库中拖拽3个Button到程序界面,分别设置Title为“添加”,“暂停”和“继续”,并且用拖拽的方式给这3个控件进行单击响应的声明,分别对应这添加操作、暂停操作、继续操作。界面如下:

iOS开发—线程的模拟暂停和继续操作

(3)进入ViewController.m文件,在单击“添加”按钮后激发的方法中,首先设置操作的最大并发操作数为1,向创建的队列中添加20个操作,然后为线程设置休眠时间为1.0s ,相当于GCD的异步串行操作;

(4)当队列中的操作正在排队时,则将调用setSuspended: 方法传入YES参数将其挂起;当队列中的操作被挂起的时候,则调用setSuspended: 方法传入NO参数让它们继续排队,代码如下:

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong)NSOperationQueue *queue;
- (IBAction)addOperation:(id)sender;
- (IBAction)pause:(id)sender;
- (IBAction)resume:(id)sender;

@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.queue=[[NSOperationQueue alloc] init];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//添加operation
- (IBAction)addOperation:(id)sender {
    //设置操作的最大并发操作数
    self.queue.maxConcurrentOperationCount=1;
    for(int i=0;i<20;i++)
    {
        [self.queue addOperationWithBlock:^{
        //模拟休眠
            [NSThread sleepForTimeInterval:1.0f];
            NSLog(@"正在下载%@%d",[NSThread currentThread],i);
        }];
    }
}
//暂停
- (IBAction)pause:(id)sender {
    //判断队列中是否有操作
    if(self.queue.operationCount==0){
        NSLog(@"没有操作");
        return;
    }
    //如果没有被挂起,才需要暂停
    if(!self.queue.isSuspended){
        NSLog(@"暂停");
        [self.queue setSuspended:YES];
    }else{
        NSLog(@"已经暂停");
    }
}
//继续
- (IBAction)resume:(id)sender {
    //判断队列中是否有操作
    if(self.queue.operationCount==0){
        NSLog(@"没有操作" );
        return;
    }
    //如果没有被挂起,才需要暂停
    if(self.queue.isSuspended){
        NSLog(@"继续");
        [self.queue setSuspended:NO];
    }else{
        NSLog(@"正在执行");
    }
    
}
@end
           

运行程序,程序的运行结果如下:

iOS开发—线程的模拟暂停和继续操作

从图中可以看出,当单击“暂停”按钮后,有一个线程还要继续并执行完毕,这是因为当队列执行暂停的时候,这个线程仍在运行,只有其余排队的线程被挂起。

继续阅读