1 前言
使用Dispatch_after ,能夠在你想指定一定數量的延遲之後,使用 GCD 來執行代碼。今天我們就來學習一下。
2 代碼執行個體
Demo1:
ZYAppDelegate.m
- (void) printString:(NSString *)paramString{ NSLog(@"%@", paramString);}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ /* 延遲三秒執行printString方法 withObject:傳的參數 */ [self performSelector:@selector(printString:) withObject:@"Grand Central Dispatch" afterDelay:3.0]; self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // 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;}
運行3秒後控制台結果:
2013-05-10 17:04:52.710 GCDAfterTest[2385:c07] Grand Central Dispatch
Demo2:
ZYAppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ //設定時間為2 double delayInSeconds = 2.0; //建立一個調度時間,相對於預設時鐘或修改現有的調度時間。 dispatch_time_t delayInNanoSeconds =dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); //延遲兩納秒執行 dispatch_queue_t concurrentQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){ NSLog(@"Grand Center Dispatch!"); }); self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // 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;}
運行2秒後控制台結果
2013-05-10 17:06:27.023 GCDAfterTest2[2435:1303] Grand Center Dispatch!
Demo3:
ZYAppDelegate.m
void processSomething(void *paramContext){ NSLog(@"Processing...");}- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ //設定時間 double delayInSeconds = 2.0; dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //調用C函數processSomething dispatch_after_f(delayInNanoSeconds, concurrentQueue, NULL, processSomething); self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // 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;}
運行2秒後控制台結果
2013-05-10 17:07:27.660 GCDAfterTest3[2476:1303] Processing...
3 結語
以上是所有內容,希望對大家有所協助。
Demo代碼下載:http://download.csdn.net/detail/u010013695/5353603