IOS 多线程 有三种主要方法 (1)NSThread (2)NSOperation (3)** 下面简单介绍这三个方法 1.NSThread 调用方法如下: 如函数需要输入参数,可从object传进去。 (1) [NSThread detachNewThreadSelector:@selector(threadInMainMethod:) toTarget:self withObject:nil]; (2) NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadInMainMethod:) object:nil]; [myThread start]; (3) [obj performSelectorInBackground:@selector(threadMe) withObject:nil]; 提个问题:如果某个ViewController里运行了一个Thread,Thread还没结束的时候,这个ViewController被Release了,结果会如何? 经过的的测试,Thread不结束,ViewController一直保留,不会执行dealloc方法。
我的线程安全解决方案 :
在NSOperation.m中的main函数中 执行回调函数之前会询问 [self isCancled] 既然阻止不了线程执行 只能想办法 让回调函数不执行 在创建operation 得对象的 dealloc方法中 首先 手动 [operation canel] 然后 [operation release]
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方法就可以了。 3.** **很强大,我的使用经验很少。但是scorpiozj 总结的比较全面(http://www.cnblogs.com/scorpiozj/archive/2011/07/25/2116459.html) 同时,这篇文章也介绍的比较详细 http://www.cnblogs.com/vinceoniphone/archive/2011/04/07/2007968.html **是和block紧密相连的,所以最好先了解下block(可以查看这里).**是C level的函数,这意味着它也提供了C的函数指针作为参数,方便了C程序员. 下面首先来看**的使用: dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
async表明异步运行,block代表的是你要做的事情,queue则是你把任务交给谁来处理了.(除了async,还有sync,delay,本文以async为例). 之所以程序中会用到多线程是因为程序往往会需要读取数据,然后更新UI.为了良好的用户体验,读取数据的操作会倾向于在后台运行,这样以避免阻塞主线程.**里就有三种queue来处理. 1. Main queue: 顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用Main Queue. 2.Serial quque(private dispatch queue) 每次运行一个任务,可以添加多个,执行次序FIFO. 通常是指程序员生成的,比如: NSDate *da = [NSDate date]; 3. Concurrent queue(global dispatch queue): 可以同时运行多个任务,每个任务的启动时间是按照加入queue的顺序,结束的顺序依赖各自的任务.使用dispatch_get_global_queue获得. 所以我们可以大致了解使用**的框架: dispatch_async(getDataQueue,^{ 由此可见,**的使用非常简单,以我的使用经验来看,以后会逐步淘汰使用NSOperation而改用**. |
本文转载至 http://blog.sina.com.cn/s/blog_4c7f7ddb0100wehz.html