异步处理1
在新线程中执行处理:
问题:应用需要执行非常耗时的任务,但是又希望用户界面保持响应,不会受到新操作的影响.
- 不开辟一个新线程的做法
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UIActivityIndicatorView*myActivityIndicator;
@property(nonatomic,strong)UIButton*myButton;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建button
self.myButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
self.myButton.frame=CGRectMake(20, 403, 280, 37);
[self.myButton addTarget:self action:@selector(bigTaskAction) forControlEvents:UIControlEventTouchUpInside];
[self.myButton setTitle:@"do long task" forState:UIControlStateNormal];
[self.view addSubview:_myButton];
//创建indicator
self.myActivityIndicator=[[UIActivityIndicatorView alloc]init];
self.myActivityIndicator.frame=CGRectMake(142, 211, 37, 37);
self.myActivityIndicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge ;
self.myActivityIndicator.hidesWhenStopped=NO;
[self.view addSubview:self.myActivityIndicator];
}
-(void)bigTask{
@autoreleasepool {
for (int i=0; i<10000; i++) {
NSString*newString=[NSString stringWithFormat:@"i=%d",i];
NSLog(@"%@ ",newString);
}
[self.myActivityIndicator stopAnimating];
}
}
//没有开辟新线程
-(void)bigTaskAction{
[self.myActivityIndicator startAnimating];
[self bigTask];
}
@end
- 开辟一个新线程
-(void)bigTaskAction{
[self.myActivityIndicator startAnimating];
//开辟新的线程
[NSThread detachNewThreadSelector:@selector(bigTask) toTarget:self withObject:nil];
}
总结:
一般情况下执行代码的时候,是一行一行的执行,上一行没有执行完成会等待,现在进行开辟线程,可同时执行 这里就是: 一边for循环在处理 ,一边指示器在界面上响应