NSThread
在UI主线程之外,利用NSThread开辟一个工作线程,让子线程执行downloadString方法(主要执行耗时操作)
1.[NSThread detachNewThreadSelector:@selector(downloadString) toTarget:self withObject:nil]; // 创建线程并调用对应的方法
2.NSThread * thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadString) object:nil];
[thread start]; // 必须调用start方法才会调用
子线程的生命周期,与子线程函数执行的生命周期一致,子线程需要单独的自动释放池,当子线程执行结束,与主线程交互,将数据传给UI主线程,子线程与主线程的通讯方式:让主线程执行某方法,将result传过去,waitUntilDone是否等待主线程操作完成再继续向下执行 [self performSelectorOnMainThread:@selector(downloadFinished:)withObject:result waitUntilDone:NO]; // 此方法在主线程执行
NSOperation
nsoperation和nsthread使用类似
开辟线程
方法一,需要调用start方法
NSInvocationOperation * operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(downloadSomthing) object:nil]; // 一般使用nsoperation的子类
[operation start]方法二,
多个线程同时执行自己的方法(异步并发操作)
[_opoerationQueue addOperation:operation]; // operationQueue 任务队列
添加多个任务到任务队列
[_opoerationQueue addOperations:(NSArray *) waitUntilFinished:(BOOL)];
执行任务对应的方法
返回结果
[self performSelectorOnMainThread:@selector(operationFinished:) withObject:result waitUntilDone:NO]; // 此方法在主线程执行
GCD (block版本的operation)
GCD中有一个主队列,来管理主线程,有三个优先级的全局队列,用来管理和维护子线程
利用全局队列开辟一个线程 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{
// 子线程对应的操作
// 操作完成后通过主队列回到主线程
dispatch_async(dispatch_get_main_queue(),^{
// 主线程对应的函数
});
});