NSThread使用

- (void)viewDidLoad {

? ? [super viewDidLoad];

? ? self.view.backgroundColor = [UIColor blackColor];

? ? UIButton * btnStart = [[UIButton alloc]initWithFrame:CGRectMake(20, 20, 300, 40)];

? ? [btnStart setTitle:@"START" forState:UIControlStateNormal];

? ? [self.view addSubview:btnStart];

? ? self.actView = [[ UIActivityIndicatorView alloc]initWithFrame:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CGRectMake(200, 100, 50, 50)];

? ?[self.view addSubview:self.actView];

? ?self.actView.activityIndicatorViewStyle =?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? UIActivityIndicatorViewStyleWhiteLarge;

? ?self.actView.hidesWhenStopped = NO;

? ?[btnStart addTarget:self action:@selector(bigTaskAction)?

? ? ? ? ? ? ? ? ? ? ? ? ? forControlEvents:UIControlEventTouchUpInside];

? ?self.aProgressView = [[UIProgressView alloc]initWithFrame:

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? CGRectMake(20, 500, 300, 20)];

? ?[self.view addSubview:self.aProgressView];

}

-(void)bigTaskAction{

? ? [self.actView startAnimating];

? ? [NSThread detachNewThreadSelector:@selector(bigTask) toTarget:self withObject:nil];

//[self bigTask];

}

-(void)bigTask{

? @synchronized(self) {

? ? int updateUIWhen = 2000;

? ? for (int i=0; i<50000; i++) {

? ? ? NSString * newString =[ NSString stringWithFormat:@"i = %i",i];

? ? ? NSLog(@"%@",newString);

? ? ? if (i==updateUIWhen) {

? ? ? ? ? float f = (float)i/50000;

? ? ? ? ? NSNumber *percentDone = [NSNumber numberWithFloat:f];

? ? ? ? ? [self performSelectorOnMainThread:

? ? ? ? ? ? ? ? ? ? ? ? ?@selector(updateProgressViewWithPercentage:)?

? ? ? ? ? ? ? ? ? ? ? ? ?withObject:percentDone ? waitUntilDone:YES];

? ? ? ? ? updateUIWhen = updateUIWhen +2000;

? ? ? ?}

}

? ? ? [self performSelectorOnMainThread:

? ? ? ? ? ? ? ? ? ? ? ? ?@selector(updateProgressViewWithPercentage:)?

? ? ? ? ? ? ? ? ? ? ? ? ?withObject:[NSNumber numberWithFloat:1.0] waitUntilDone:YES];

? ? ? ?[self.actView stopAnimating];

? }

}

-(void)updateProgressViewWithPercentage:(NSNumber *)percentDone {

? ? ? [self.aProgressView setProgress:[percentDone floatValue] animated:YES];

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容