ios-多线程讲解

来源:互联网 发布:void 0 js 等于什么 编辑:程序博客网 时间:2024/06/05 16:20

ios有三种主要方法:1、NSThread。2、NSOperation。3、GCD。

1、  NSThread:
NSThread的调用方法如下几种:如果需要函数参数的话,可以通过Object传递。
1.1:

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


1.2:

NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadInMainMethod:) object:nil];

[myThread start];

1.3:

[obj performSelectorInBackground:@selector(threadMe) withObject:nil];

2、  NSOperation:

NSOperation也是多线程的一种,NSOpertaion有2种形式.(1) 并发执行并发执行你需要重载如下4个方法 //执行任务主函数,线程运行的入口函数    

- (void)start

//是否允许并发,返回YES,允许并发,返回NO不允许。默认返回NO

-(BOOL)isConcurrent - (BOOL)isExecuting

//是否已经完成,这个必须要重载,不然放在放在NSOperationQueue里的NSOpertaion不能正常释放。

- (BOOL)isFinished

比如TestNSOperation:NSOperaion 重载上述的4个方法,
声明一个NSOperationQueue,

NSOperationQueue *queue = [[[NSOperationQueue alloc ] init] autorelease];
[queue addOperation:testNSoperation];


它会自动调用TestNSOperation里的 start函数,如果需要多个NSOperation,你需要设置queue的一些属性,如果多个NSOperation之间有依赖关系,也可以设置,具体可以参考API 文档。  (2)非并发执行

-(void)main

只需要重载这个main方法就可以了。

官方教程
GCD是和block紧密相连的,所以最好先了解下block(可以查看这里).GCD是C level的函数,这意味着它也提供了C的函数指针作为参数,方便了C程序员.
下面首先来看GCD的使用:
1 dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了.(除了async,还有sync,delay,本文以async为例).
之所以程序中会用到多线程是因为程序往往会需要读取数据,然后更新UI.为了良好的用户体验,读取数据的操作会倾向于在后台运行,这样以避免阻塞主线程.GCD里就有三种queue来处理。
1. Main queue:
  顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用Main Queue.
2.Serial quque(private dispatch queue)
  每次运行一个任务,可以添加多个,执行次序FIFO. 通常是指程序员生成的,比如:
NSDate *da = [NSDate date];
NSString *daStr = [da description];
const char *queueName = [daStr UTF8String];
dispatch_queue_t myQueue = dispatch_queue_create(queueName, NULL);
3. Concurrent queue(global dispatch queue):
可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.
所以我们可以大致了解使用GCD的框架:
dispatch_async(getDataQueue,^{
    //获取数据,获得一组后,刷新UI.
    dispatch_aysnc (mainQueue, ^{
    //UI的更新需在主线程中进行
};
}
)



0 0
原创粉丝点击