6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Objective-Cのblockの定義の仕方とか、関数への渡し方とかのまとめ。

Blockの基本

^(int n) {
    return n + 1;
};

int (^plusOne) (int) = ^(int n) {
    return n + 1;
};

型宣言

同じようなBlockを作成したい場合はよくあるので、その場合は型を宣言しておくことができる。

typedef int (^PlusOne)(int);

PlusOne plusOne = ^(int n) {
    return n + 1;
};

レキシカルスコープ

Blockの中ではBlockの中で定義した変数しか参照できないが__block修飾子をつけると特別にBlockの中からでも参照できるようになる。

__block int x = 100;
void (^print)(void) = ^(void) {
    NSLog("%d", x);
};
print();  // 100が表示される

メソッドの引数として渡す

このような形でメソッドの宣言をする

- (void)oneWithFunc:(int (^)(int))func {
    int n = 1;
    return func(n);
}

呼ぶときはこんな感じ。

[myObject oneWithFunc:^(int n) {
    return n * 2;
}];

// 1 * 2で2が返ってくる
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?