15、摇奖机案例

摇奖机案例
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lbl1;
@property (weak, nonatomic) IBOutlet UILabel *lbl2;
@property (weak, nonatomic) IBOutlet UILabel *lbl3;
@property (weak, nonatomic) IBOutlet UIButton *startButton;

//全局队列
@property (nonatomic, strong) NSOperationQueue *queue;
@end

@implementation ViewController
//懒加载
- (NSOperationQueue *)queue {
if (_queue == nil) {
_queue = [NSOperationQueue new];
}
return _queue;
}

//点击开始执行
- (IBAction)start:(UIButton *)sender {
//当队列中有操作的时候,不添加操作
if (self.queue.operationCount == 0) {
//异步执行 添加操作
[self.queue addOperationWithBlock:^{
[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];

}
}

//随机生成3个数字,显示到label上
- (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:^{
//给label赋值
self.lbl1.text = [NSString stringWithFormat:@"%d",num1];
self.lbl2.text = [NSString stringWithFormat:@"%d",num2];
self.lbl3.text = [NSString stringWithFormat:@"%d",num3];
}];

}
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSLog(@"%zd",self.queue.operationCount);
}

@end



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值