您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發(68):最簡單的多執行緒寫法

編輯:iOS 開發綜合

前言

想把耗時運算丟到背景執行,又不希望直接面對 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

必讀的三個注意事項

  • @autoreleasepool 不能省:背景執行緒沒有現成的 autorelease pool,不加的話物件無法被妥善釋放, Instruments 下會看到記憶體持續攀升。
  • 不要碰 UI:所有 UIKit 操作都必須回到主執行緒。要更新畫面,請用 performSelectorOnMainThread:withObject:waitUntilDone: 或改用 GCD 的 dispatch_get_main_queue()。
  • 它是拋棄式的:這個方法無法取消、無法查詢進度、也無法設優先權。正式專案中若需要這些能力, GCD 或 NSOperationQueue 才是更合適的選擇。

因此,performSelectorInBackground: 的定位很清楚:適合快速把一段一次性的、不需要回收控制的運算丟到背景,程式碼最少、語意最直白。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved