Download
slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
GCD 介绍 PowerPoint Presentation

GCD 介绍

114 Vues Download Presentation
Télécharger la présentation

GCD 介绍

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. GCD介绍 Grand Central Dispatch

  2. Agenda • GCD简介 • 应用示例 • Demo • 其他

  3. GCD简介 Grand Central Dispatch (GCD) comprises new language features, runtime libraries, and system enhancements that provide systemic, comprehensive improvements to the support for concurrent code execution on multicore hardware in iOS and Mac OS X. 简而言之,是Apple的提供的基于操作系统底层的多核编程的API库

  4. 应用示例 – 用户认证和信息获取 • 假设有个需求如下 Step1:用户认证: 用户输入用户名密码 从网络认证用户信息 显示用户认证成功 Step2:用户信息获取: 如果认证成功,则从网络请求用户信息 显示用户信息 要求:异步处理,不阻塞界面操作

  5. 现在想想这个需求的实现方式?- 要创建线程吗?- 要多少个类和方法?- 线程之间的数据如何传递? GCD可以做到: 优雅  + 高性能

  6. GCD实现:一个方法解决问题 dispatch_asyn(workingQueue, ^{ BOOL result = [self sendUserAuthentication(user, password)]; dispatch_asyn(dispatch_get_main_queue(), ^{ if (result == YES){ [self displayAuthenticationSuccess]; dispatch_asyn(workingQueue, ^{ NSString* user = [self sendGetUserInfo]; dispatch_asyn(dispatch_get_main_queue(), ^{ [self displayUserInfo]; }); }); } else{ [self displayAuthenticationFailure]; } }); });

  7. Demo

  8. GCD的基础 • block programming Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. 基于C语言的可执行的代码块 int multiplier = 7; int (^myBlock)(int) = ^(int num) { return num * multiplier; }; printf("%d", myBlock(3)); // prints "21"

  9. GCD的主要API • 队列创建和销毁 disptach_create dispatch_release • 分发消息到队列 dispatch_asyn dispatch_sync • 获得界面主线程队列 dispatch_get_main_queue

  10. 其他 • 尽管代码变得优雅简洁,但是多线程的知识还是必不可少,需要减少资源冲突和注意多线程并发访问 • 有些时候也还是需要使用更高层的API NSThread NSOperation & NSOperationQueue