Learn C blocks in 20 seconds

Guides | Tutorial By 6 years ago

Since the introduction of iOS4, blocks have become very prevalent in the Cocoa framework as a quick and non messy way of implementing a ‘callback’. Blocks can be passed around just like any other variable. They are most used in UIView animations.

Harnessing the power and simplicity of blocks is something that I have been doing a lot more since iOS4, turning old fashioned protocol delegates into blocks where it makes sense.

I will compare blocks to their C function counterparts, for terms of simplicity and explanation.

double MyFunction (int input1, void* input2)
{
	return 0;
}

int main(int argc, char *argv[])
{
	//	Traditional C function
	MyFunction(1, NULL);

	//	C block function
	double (^VariableName)(int, void*) = ^ double (int input1, void* input2)
	{
		return 0;
	};

	VariableName(1, NULL);

	return 0;
}

Repeating the block creation code for the same structured block can be annoying, you can create a typedef for it like so

typedef double (^MyBlock)(int, void*);

The old block creation code can be replaced using the typedef

MyBlock VariableName = ^ double (int input1, void* input2)
{
	return 0;
};

That is C Blocks in a nutshell, the only other methods to use in conjunction with these is Block_copy and Block_release.