IOS开发基础之摇奖机案例

IOS开发基础之摇奖机案例

在这里插入图片描述

//  ViewController.m
//  33-摇奖机器
//  Created by 鲁军 on 2021/3/9.
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lbl1;
@property (weak, nonatomic) IBOutlet UILabel *lbl2;
@property (weak, nonatomic) IBOutlet UILabel *lbl3;
- (IBAction)start:(id)sender;
@property (weak, nonatomic) IBOutlet UIButton *startButton;
//全局队列
@property(nonatomic,strong)NSOperationQueue *queue;
@end

@implementation ViewController
- (NSOperationQueue *)queue{
    if(_queue==nil){
    _queue = [[NSOperationQueue alloc] init];
    //设置最大并发数  (并不是线程数字)
    //_queue.maxConcurrentOperationCount = 2;
    }
    return _queue;
}
- (void)viewDidLoad {
    [super viewDidLoad];
   }
- (IBAction)start:(UIButton *)sender {
    //当队列中有操作的时候 不添加操作
    if(self.queue.operationCount ==0){
    //卡死  界面卡死
    //异步执行
     [self.queue addOperationWithBlock:^{
     //  NSLog(@"%d,%@",i,[NSThread currentThread]);
     [self random];
     }];
     //设置文字
     [self.startButton setTitle:@"暂停" forState:UIControlStateNormal];
     self.queue.suspended = NO;
     }else if(!self.queue.isSuspended){
      //正在执行
      //先把当前的操作执行完 暂停后续的操作
      self.queue.suspended = YES;
      //设置文字
      [self.startButton setTitle:@"继续" forState:UIControlStateNormal];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    // 操作数
    NSLog(@"%zd",self.queue.operationCount);
}
-(void)random{
    while(!self.queue.isSuspended){
        [NSThread sleepForTimeInterval:0.05];
        // [0,10)   0-9
        int num1 = arc4random_uniform(10);
        int num2 = arc4random_uniform(10);
        int num3 = arc4random_uniform(10);
        //回到主线程上更新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        self.lbl1.text = [NSString stringWithFormat:@"%d",num1];
        self.lbl2.text = [NSString stringWithFormat:@"%d",num2];
        self.lbl3.text = [NSString stringWithFormat:@"%d",num3];
    }];
  }
}
@end

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值