IOS开发基础之摇奖机案例
#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];
}
return _queue;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (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];
}
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSLog(@"%zd",self.queue.operationCount);
}
-(void)random{
while(!self.queue.isSuspended){
[NSThread sleepForTimeInterval:0.05];
int num1 = arc4random_uniform(10);
int num2 = arc4random_uniform(10);
int num3 = arc4random_uniform(10);
[[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