一:多线程
1,NSThread创建线程
a,NSThread的类方法创建线程
[NSThread detachNewThreadSelector:@selector(doing) toTarget:self withObject:nil];
withObject 参数 下面几个方法类似
b,构造方法创建线程需要start
NSThread *th=[[NSThread alloc]initWithTarget:self selector:@selector(doing) object:nil];
[th start];
c,View创建
[self performSelectorInBackground:@selector(doing) withObject:nil];
2,Operation创建线程
a,Operation创建线程
//创建 Operation队列,add创建
NSOperationQueue *queue =[[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
//执行方法
}];
b,Operation启动多个线程,可设置线程的优先级
NSInvocationOperation *operation1=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:@"1"];
NSInvocationOperation *operation2=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadImage:) object:@"2"];
[operationQueue addOperation:operation1];
[operationQueue addOperation:operation2];
3,GCD创建线程
dispatch_queue_t queue=dispatch_queue_create("baihe", nil);
dispatch_async(queue, ^{
});
二:定时器
看下面的定时器操作
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doing) userInfo:nil repeats:YES];该语句可能不会输出 ,可能会被return
解决办法://获得当前线程,防止被return,无法执行
[[NSRunLoopcurrentRunLoop] run];
一般不在主线程中执行定时操作,开启线程使用自动释放池操作
/**
TimerInterval : 执行之前等待的时间。比如设置成1.0,就代表1秒后执行方法
target : 需要执行方法的对象。
selector : 需要执行的方法
repeats : 是否需要循环
*/
@autoreleasepool {
NSTimer *timer=
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doing) userInfo:nil repeats:YES];
//RUNLoop管理定时器
// [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
//获得当前线程,防止被return,无法执行
[[NSRunLoop currentRunLoop] run];
// [timer invalidate];//停止定时器