LoginSignup
120
116

More than 5 years have passed since last update.

iOSで最も簡単にマルチスレッド処理を行う方法(NSOperationQueue)

Last updated at Posted at 2015-01-04

目的

時間のかかる処理に関しては、メインスレッドとは別のスレッドで並列的に処理を行いたいことがある。
調べてみると、iOSアプリの実装で別スレッド処理を行う方法はいくつかみつかった。ただ、できるだけ簡単な記述を探すのに意外と時間がかかったのでメモしておく。

(2015/04/01 更新: swiftでの記述を追記)

最も簡単な実装

調べた内容を総合した所、NSOperationQueueを使うのが最も簡単のようだ。

別スレッドを一つだけ実行する場合

Objective-C

sample.m
- (void)test {
    [[[NSOperationQueue alloc] init] addOperationWithBlock:^{
        NSLog(@"Some Operation.");
    }];
}

swift

sample.swift
func test() {
    NSOperationQueue().addOperationWithBlock({ () -> Void in
        println("Some Operation.")
    })
}

別スレッドを複数実行する場合

Objective-C

sample.m
- (void)test2 {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];

    [queue addOperationWithBlock:^{
        NSLog(@"Some Operation");
    }];

    [queue addOperationWithBlock:^{
        NSLog(@"Another Operation");
    }];

    // 以降必要なだけaddOperationする
}

swift

sample.swift
func test2() {
    let queue = NSOperationQueue()

    queue.addOperationWithBlock { () -> Void in
        println("Some Operation.")
    }

    queue.addOperationWithBlock { () -> Void in
        println("Another Operation.")
    }

    // 以降必要なだけaddOperationする
}

別スレッド処理を行える他の方法について

調べてみたところ、別スレッド処理を行うためには大きく分けて次の3つの方法があるらしい。

  1. NSOperationQueueを使う方法
  2. GCD(Grand Central Dispatch)を使う方法
  3. NSThreadを使う方法

まず、GCDがNSThreadより良い点については以下のような理由があるようだ。

GCDがよく利用されています。NSThreadだとスレッドの処理などを自前で書かないといけないのでコードが冗長になってしまい大変です。

出典: 8.2 Grand Central Dispatch · mixi-inc/iOSTraining Wiki

次は、GCDとNSOperationQueueのどちらを使うかに関して。今回調べた範囲では、基本的には高いレイヤー(Cocoa)の実装である後者を利用したら良いのではという印象。

今回見つけた関連URLを以下にまとめたので、もっと詳しい情報を得たい方は参考にしてみてほしい。

参考

ちくわとチワワはよく似てる — 非同期に処理を呼び出したい
http://thata.tumblr.com/post/20235526244

8.2 Grand Central Dispatch · mixi-inc/iOSTraining Wiki
https://github.com/mixi-inc/iOSTraining/wiki/8.2-Grand-Central-Dispatch

ios - NSOperation vs Grand Central Dispatch - Stack Overflow
http://stackoverflow.com/questions/10373331/nsoperation-vs-grand-central-dispatch

ios - Which is the best of GCD, NSThread or NSOperationQueue? - Stack Overflow
http://stackoverflow.com/questions/12995344/which-is-the-best-of-gcd-nsthread-or-nsoperationqueue

NSOperationQueue スレッドと処理の関係 - A Day In The Life
http://d.hatena.ne.jp/glass-_-onion/20110527/1306499056

【iPhoneアプリ】これを使えるようにならないと「マルチスレッド」について 概要編 - ゆるい感じのプログラムを書きたい。
http://kassans.hatenablog.com/entry/2014/03/13/125332

【iPhoneアプリ】これを使えるようにならないと「マルチスレッド」について 実装編 - ゆるい感じのプログラムを書きたい。
http://kassans.hatenablog.com/entry/2014/03/14/125810

【iPhoneアプリ】他にもまだまだあった「マルチスレッド」について dispatch_xxxxx編 - ゆるい感じのプログラムを書きたい。
http://kassans.hatenablog.com/entry/2014/03/25/183257

120
116
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
120
116