`
wenzongliang
  • 浏览: 448885 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

IOS线程

 
阅读更多

 

ios有三种主要方法:1NSThread2NSOperation3GCD

 

1、  NSThread

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

 

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

 [myThread start]; 

 

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

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

 

2、  NSOperation:

 

NSOperation是一个任务,一个NSOperationQueue至少拥有一个线程,可配置。  

NSOperationQueue *queue = [[[NSOperationQueue alloc ] init] autorelease];

TestNSOperation *testNSOperation=[[[TestNSOperation alloc ] init] autorelease];//TestNSOperation继承NSOperation

[queue addOperation:testNSoperation]; 

 

 

NSInvocationOperation是NSOperation的一种实现

 

 

NSInvocationOperation *invocOperation = [[NSInvocationOperation alloc]
		 initWithTarget:self selector:@selector(doSomeThing) 
object:nil]; 
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
	[aQ setMaxConcurrentOperationCount:10];
[operationQueue addOperation:invocOperation];

 

 

NSOpertaion有2种形式.

(1) 并发执行

       并发执行你需要重载如下4个方法

     //执行任务主函数,线程运行的入口函数

    - (void)start 

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

    -(BOOL)isConcurrent 

    - (BOOL)isExecuting

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

   - (BOOL)isFinished

(2)非并发执行

  -(void)main

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

 

 

 

3、  GCD

GCD是和block紧密相连的,所以最好先了解下block(可以查看这里).GCD是C level的函数,这意味着它也提供了C的函数指针作为参数,方便了C程序员.

下面首先来看GCD的使用:

 

dispatch_async(dispatch_queue_t  queue, dispatch_block_t  block);

async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了.有三种queue。一个queue相当于一个线程。

1. 主线程队列 Main queue:

  顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用Main Queue.

 

2.串行的队列 Serial quque(private dispatch queue)

  每次运行一个任务,可以添加多个任务,执行次序FIFO. 通常是指程序员生成的,比如:

1

dispatch_queue_t  myQueue = dispatch_queue_create(queueName, NULL);

 

3.并行队列 Concurrent queue(global dispatch queue):

可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得.

所以我们可以大致了解使用GCD的框架:

1

2

3

4

5

6

7

dispatch_async(queue,^{//获取数据,获得一组后,刷新UI.

    dispatch_aysnc (mainQueue, ^{//UI的更新需在主线程中进行};

  }

);

由此可见,GCD的使用非常简单,以我的使用经验来看,以后会逐步淘汰使用NSOperation而改用GCD。

提个问题:如果某个ViewController里运行了一个Thread,Thread还没结束的时候,这个ViewController被Release了,结果会如何? 

经过的的测试,Thread不结束,ViewController一直保留,不会执行dealloc方法。

我的话费充值店-各种面额
电信100元仅售98.60 

联通100仅售99.00
移动100仅售99.30

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics