iOS 多线程

IOS应用开发中我们可以使用如下三种方式来实现程序的多线程执行:

1、NSThread 
2、Cocoa NSOperation (使用NSOperation和NSOperationQueue)
3、GCD  (Grand Central Dispatch)


 三种方式抽象度层次是从低到高的,抽象度越高的使用越简单,也是Apple最推荐使用的,各有缺点介绍:
1.NSThread:
优点:NSThread 比其他两个轻量级。
缺点:需要自己管理线程的生命周期,线程同步,线程同步时对数据的加锁会有一定的系统开销。
cocoa给我提供了两种方法生成线程:

 

- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument

NSThread* thread = [[NSThread alloc] initWithTarget:self  
                                        selector:@selector(do:)  
                                        object:nil];  
[thread start];

+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument

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

cocoa中的一些函数也会单独开辟一个线程执行我们的操作如:

 

- (id)performSelector:(SEL)aSelector;

- (id)performSelector:(SEL)aSelector withObject:(id)object;

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;

 

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg NS_AVAILABLE(10_5, 2_0);

.......2.Cocoa Operation 
优点:不需要关心线程管理,数据同步的事情。
Cocoa Operation 相关的类是 NSOperation ,NSOperationQueue。NSOperation是个抽象类,使用它必须用它的子类,可以实现它或者使用它定义好的两个子类:NSInvocationOperation 和 NSBlockOperation。创建NSOperation子类的对象,把对象添加到NSOperationQueue队列里执行,我们会把我们的执行操作放在NSOperation中main函数中。


3.GCD
Grand Central Dispatch (GCD)是Apple开发的一个多核编程的解决方法,GCD是一个替代诸如NSThread, NSOperationQueue, NSInvocationOperation等技术的很高效和强大的技术。它让程序平行排队的特定任务,根据可用的处理资源,安排他们在任何可用的处理器核心上执行任务,一个任务可以是一个函数(function)或者是一个block。

dispatch queue分为下面三种:
private dispatch queues,同时只执行一个任务,通常用于同步访问特定的资源或数据。
global dispatch queue,可以并发地执行多个任务,但是执行完成的顺序是随机的。
Main dispatch queue 它是在应用程序主线程上执行任务的。

如我们使用GCD执行异步操作:

 

//check version

        dispatch_async(dispatch_get_global_queue(00), ^{

            // 处理耗时操作的代码块...

            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:getAppVersion,SERVER_IP]];

            

            NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];

            NSData *receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:nilerror:nil];

            

            if (receivedData == nil || receivedData.length == 0) {

                return;

            }

            

            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];

            NSString *server_version = [dict objectForKey:@"AppVersion_Apple"];

            

            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];

            //app build版本

            NSString *install_version = [infoDictionary objectForKey:@"CFBundleVersion"];

            

            if([install_version floatValue] < [server_version floatValue])//new

            {

                dispatch_async(dispatch_get_main_queue(), ^{

                    //回调通知主线程刷新,

                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:[NSStringstringWithFormat:@"Please update to latest version from the server"] delegate:self cancelButtonTitle:@"Not Allow" otherButtonTitles:@"Update",nil];

                    alertView.tag = 3;

                    [alertView show];

                });

            }

            NSLog(@"****%@",dict);

            //通知主线程刷新

        });

 

原文地址:https://www.cnblogs.com/iOS-mt/p/4091096.html