LoginSignup
38
40

More than 5 years have passed since last update.

【GCD】実行キューのラベルを取得する

Last updated at Posted at 2015-01-16

iOS の GCD で処理を実行したときに、「本当にこのキューで実行されてるのかな?」と確認したくなったときに、実行キューのラベルを確認する方法。

ここでいう「ラベル」とは、

dispatch_queue_t queue = dispatch_queue_create("com.shu223.hoge", DISPATCH_QUEUE_SERIAL);

みたいに dispatch_queue_create()キューを生成する際に第1引数に指定する文字列です。

dispatch_queue_get_label

ラベルを取得するには、dispatch_queue_get_label() という関数が使用できます。

// Create a GCD object:
dispatch_queue_t someQueue = dispatch_queue_create("someQueue", nil);

// put a block on the queue, the queue retains the block.
dispatch_async(someQueue, ^{
    // capture the GCD object inside the block,
    // the block retains the queue and BAM! retain cycle!
    const char *label = dispatch_queue_get_label(someQueue);
    NSLog(@"%s", label);
});

(参考:http://amattn.com/p/grand_central_dispatch_gcd_summary_syntax_best_practices.html

DISPATCH_CURRENT_QUEUE_LABEL

ただ、dispatch_queue_get_label だと、引数にキューを渡さないといけないので、 dispatch_async でディスパッチしたわけじゃない場合に困る。

たとえば Core Bluetooth でセントラルマネージャのイベントディスパッチ用のキューを次のように指定した場合。

// キューを保持するプロパティ
@property (nonatomic, strong) dispatch_queue_t centralQueue;
// セントラルのイベントをディスパッチするキューの作成
self.centralQueue = dispatch_queue_create("com.shu223.BLEExample", DISPATCH_QUEUE_SERIAL);

// キューを指定してセントラルマネージャを初期化
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                           queue:self.centralQueue];

各種デリゲートメソッドが呼ばれるときに、実行キューがちゃんと指定したものかどうかを確認したい、でも「現在実行しているキューのオブジェクトの取得方法」がよくわからん。。

・・・前置きが長くなりましたが、DISPATCH_CURRENT_QUEUE_LABEL を使用して次のようにすればOKでした。

const char *label = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
NSLog(@"実行キュー: %s", label);

先のCore Bluetoothのセントラルマネージャの例でいえば、こんな感じで実行キューを確認できます。

- (void)   centralManager:(CBCentralManager *)central
    didDiscoverPeripheral:(CBPeripheral *)peripheral
        advertisementData:(NSDictionary *)advertisementData
                     RSSI:(NSNumber *)RSSI
{
    const char *label = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
    NSLog(@"実行キュー: %s", label);
}

Swiftの場合

swift2
let label = dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL)
print(String(format: "queue label: %s", label))
swift3
let label = String(validatingUTF8: __dispatch_queue_get_label(nil))!
print(String(format: "queue label: %s", label))

ちなみに

print("queue label: \(label)")

だけだとちゃんと文字列として表示してくれませんでした。

参考

38
40
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
38
40