7
7

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.

# Block文法

Last updated at Posted at 2012-04-10

皆でよく忘れる Block の文法メモ

メモっつーかコピペ

無名コール

int
main (void)
{
	@autorelease {
		^{ NSLog("None labeling."); }(); // 変数に入れず実行
	}
}

変数にいれて呼び出す

int
main (void)
{
	@autorelease {
		// 一度変数に入れて実行
		void (^labeling)(NSObject*) = ^(NSObject* obj){
			NSLog(@"Labeling: %@", obj);
		};
		labeling(@"おっぱい");
	}
}

関数の引数にBlockを渡す

一部、簡略化するために未実装の文法(XCode 4.3)の文法使ってます

  1. @10 は [NSNumber numberWithInto:10] と等価
  2. @[~..] は [NSArray arrayWithObjects:~..,nil] と等価 (ただこれ、+[NSArray arrayWithObjects:] なんだろうか、それとも +[NSArray arrayWithObjects:count:] なんだろうか…)

ex: Objective-C Literals

# include <Block.h>

void intforeach(NSArray *array, void(^callback)(int))
{
	for (NSNumber n in array)
		callback([n intValue]);
}

int main (int argc, const char * argv[]) {
	@autorelease {
		intforeach(@[@10, @20, @30],
			^ (int number) {
				NSLog(@"%d", number);
			});
	}
	return 0;
}

Block を返す関数

(何かここから下の表示が太文字になってバグってるけど気にしない…)

# include <Block.h>
typedef int (^IntBlock)();

IntBlock
counter (int start, int increment)
{
	__block int i = start;
	
	return Block_copy( ^ {
		int ret = i;
		i += increment;
		return ret;
	});
}

int
main (void)
{
	@autorelease {
		IntBlock mycounter = counter(5, 2);
		printf("First call: %d\n", mycounter());
		printf("Second call: %d\n", mycounter());
		printf("Third call: %d\n", mycounter());
	
		Block_release(mycounter);
	
	}
	return 0;
}

参考:

7
7
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?