想把耗時運算丟到背景執行,又不希望直接面對 NSThread 的細節?NSObject 的 performSelectorInBackground:withObject: 就是最省事的入口:一行程式碼,把一個方法丟到新的背景執行緒去跑。
- (void) firstCounter{
@autoreleasepool {
NSUInteger counter = 0;
for (counter = 0; counter < 10; counter++){
NSLog(@"First Counter = %lu", (unsigned long)counter);
}
}
}
- (void) secondCounter{
@autoreleasepool {
NSUInteger counter = 0;
for (counter = 0; counter < 10; counter++){
NSLog(@"Second Counter = %lu", (unsigned long)counter);
}
}
}
- (void) thirdCounter{
@autoreleasepool {
NSUInteger counter = 0;
for (counter = 0; counter < 10; counter++){
NSLog(@"Third Counter = %lu", (unsigned long)counter);
}
}
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// 各在新的背景執行緒上呼叫
[self performSelectorInBackground:@selector(firstCounter) withObject:nil];
[self performSelectorInBackground:@selector(secondCounter) withObject:nil];
[self performSelectorInBackground:@selector(thirdCounter) withObject:nil];
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
三個計數迴圈交錯輸出,且執行緒 ID 各不相同(3b03、3903、4003):
2013-05-12 21:37:23.654 [417:3b03] Second Counter = 0 2013-05-12 21:37:23.654 [417:3903] First Counter = 0 2013-05-12 21:37:23.654 [417:4003] Third Counter = 0 2013-05-12 21:37:23.657 [417:3b03] Second Counter = 1 2013-05-12 21:37:23.657 [417:3903] First Counter = 1 ... 2013-05-12 21:37:23.675 [417:3903] First Counter = 9
performSelectorOnMainThread:withObject:waitUntilDone: 或改用 GCD 的 dispatch_get_main_queue()。因此,performSelectorInBackground: 的定位很清楚:適合快速把一段一次性的、不需要回收控制的運算丟到背景,程式碼最少、語意最直白。