1 前言
本章作为入门,我们将介绍介绍一下,能使用GCD执行UI操作。
2 代码实例
ZYViewController.h
#import <UIKit/UIKit.h>
@interface ZYViewController : UIViewController
@end
ZYViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
//dispatch_queue_t:一个调度队列是一个轻量级的对象,你的应用程序提交模块的后续执行。获得主队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
/*
提交一个块为异步执行在一个调度队列,并立即返回。
队列
队列来提交块。队列是由系统保留直到块已经运行到完成。该参数不能为空。
块
块提交到目标调度队列。这个函数执行块复制和释放调用者。该参数不能为空。
*/
dispatch_async(mainQueue, ^(void)
{
[[[UIAlertView alloc] initWithTitle:@"GCD"
message:@"GCD is amazing!"
delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil] show];
});
}
ZYAppDelegate.h
#import <UIKit/UIKit.h>
@class ZYViewController;
@interface ZYAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ZYViewController *viewController;
@end
ZYAppDelegate.m
//声明结构体AlertViewData
typedef struct{
char *title;
char *message;
char *cancelButtonTitle;
} AlertViewData;
@implementation ZYAppDelegate
//C函数
void displayAlertView(void *paramContext){
AlertViewData *alertData = (AlertViewData *)paramContext; NSString *title =
[NSString stringWithUTF8String:alertData->title];
NSString *message =
[NSString stringWithUTF8String:alertData->message];
NSString *cancelButtonTitle =
[NSString stringWithUTF8String:alertData->cancelButtonTitle];
[[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:cancelButtonTitle
otherButtonTitles:nil, nil] show];
free(alertData);
}
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//获得主线程队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
AlertViewData *context = (AlertViewData *) malloc(sizeof(AlertViewData));
if (context != NULL){
context->title = "GCD";
context->message = "GCD is amazing.";
context->cancelButtonTitle = "OK";
dispatch_async_f(mainQueue,
(void *)context,
displayAlertView);
//输出当前线程
NSLog(@"Current thread = %@", [NSThread currentThread]);
//输出主线程
NSLog(@"Main thread = %@", [NSThread mainThread]);
}
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.window.backgroundColor = [UIColor whiteColor];
// Override point for customization after application launch.
self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
运行结果
控制台结果
2013-05-10 10:59:21.871 GCDExcuteUITest[1661:c07] Current thread = <NSThread: 0x7113d00>{name = (null), num = 1}
2013-05-10 10:59:21.872 GCDExcuteUITest[1661:c07] Main thread = <NSThread: 0x7113d00>{name = (null), num = 1}
3 结语
以上是全部内容,希望对大家有所帮助。