使用 NSOperation 实现多个弹框顺序弹出

     最近公司需要找几个新人,面试过程中发现大部分面试者都对多线程使用甚是微少(其实本人在开发过程中也是很少用到多线程),只是看到一些源码例如 SDWeImage 处理多任务时用到了 NSOperationQue ,正好这几天开发中有遇到了多个弹框一次性弹出的问题,尽管现实中很少会出现这样的现象,但是在联调过程中如果多个接口不同,然后报错就会有 N个错误弹框出现在窗口上,很不友好,于是就稍作的研究,写了一个这样的 demo,感觉对多线程的使用也只是冰山一角,聊作玩耍吧

  其实多线程的使用并没有想象那么神秘,尤其是使用Apple封装过得 NSOperation 和 NSOperationQue 组合,至于它相对于 GCD的优缺点在这里就不多赘述了(网上一搜一大堆),直接上效果图

文件代码:

 1 #import "customOperation.h"
 2 #import "MBProgressHUD.h"
 3 
 4 //创建全局的队列
 5 static NSOperationQueue* globalAlertOperationQue(){
 6     static NSOperationQueue* que ;
 7     static dispatch_once_t onceToken;
 8     dispatch_once(&onceToken, ^{
 9         que = [[NSOperationQueue alloc]init];
10         que.maxConcurrentOperationCount=1;
11     });
12     return que;
13 }
14 
15 
16 void showToast(NSString*str,UIView* view){
17     customOperation *operation =[[customOperation alloc]initWithView:view title:str];
18     [globalAlertOperationQue() addOperation:operation];
19 }
20 
21 
22 @implementation customOperation
23 @synthesize executing = _executing;
24 @synthesize finished = _finished;
25 - (id)initWithView:(UIView *)view title:(NSString *)title{
26     if (self==[super init]) {
27         _view=view;
28         _title=title;
29     }
30     return self;
31 }
32 -(void)start{
33     self.executing = YES;
34         dispatch_async(dispatch_get_main_queue(), ^{  //执行UI操作需要回到主线程
35                MBProgressHUD *temphud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
36             temphud.yOffset=200;
37             temphud.mode = MBProgressHUDModeText;
38             temphud.detailsLabelText =self.title;
39             [temphud hide:YES afterDelay:2];
40         });
41         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
42             [self done]; //为了显示效果,需要延迟finish才可以出来效果
43         });
44 }
45 
46 //一个operation完成后才会执行下一个操作
47 - (void)done {
48     self.finished = YES;
49     self.executing = NO;
50 }
51 
52 #pragma mark - setter -- getter
53 - (void)setExecuting:(BOOL)executing {
54     //调用KVO通知
55     [self willChangeValueForKey:@"isExecuting"];
56     _executing = executing;
57     //调用KVO通知
58     [self didChangeValueForKey:@"isExecuting"];
59 }
60 
61 - (BOOL)isExecuting {
62     return _executing;
63 }
64 
65 - (void)setFinished:(BOOL)finished {
66     if (_finished != finished) {
67         [self willChangeValueForKey:@"isFinished"];
68         _finished = finished;
69         [self didChangeValueForKey:@"isFinished"];
70     }
71 }
72 
73 - (BOOL)isFinished {
74     return _finished;
75 }
76 
77 // 返回NO 标识为串行Operation
78 - (BOOL)isAsynchronous {
79     return NO;
80 }

完整 Demo地址:  https://github.com/HouSaiYinKay/SerieToast/blob/master/customToast/customOperation.m

猜你喜欢

转载自www.cnblogs.com/tuikai/p/11789190.html