[BlocksIt refersFunction pointer]
Blocks was first transplanted from the local snow leopard of Apple to the iPhone. Blocks is widely used in multithreading.
(1) What is Blocks?
(2) differences between Blocks and c voice function pointers
(3) how to call Blocks
(4) How does proxy 2 communicate through Blocks
(1) What is Blocks?
Similar to the c speech function pointer, running requires support for compilers and Runtime (ios4.0 starts to support Blocks)
Blocks is used for communication between two objects, which is equivalent to a callback function.
(2) differences between Blocks and c voice function pointers
(3) how to call Blocks
Typedef definition:
_ Block Keyword:
Change to a global variable
Simple use of blocs:
Block statement:
Void (^ myblocks) (void) = NULL;
Block assignment:
Myblocks = ^ (void ){
NSLog (@ "in blocks ");
};
Block call:
Myblocks ();
Example 1:
Int (^ myblocks2) (int a, int B) = ^ (int a, int B) {// value int c = a + B; return c ;} int ret = myblocks2 (10, 20); // Execute
Example 2:
_ Block int sum = 0; // The global variable int (^ myblocks3) (int a, int B) = ^ (int a, int B) {sum = a + B; return sum;} myblock3 (20, 30 );
Example 3:
Typedef int (^ SumBlockT) (int, int); // defines a type of SumBlockT myblocks4 = ^ (int a, int B) {NSLog (@ "sum: % d ", a + B); return 0;} myblock4 (10, 12 );
(4) How does proxy 2 communicate through Blocks
Blocks Used for iphone development:
Define a blocks. The dog calls this blocks at a time;
A blocks is defined in a dog to store the blocks function defined in a person.
Dog:
. H
Void (^ BarkCallback) (Dog * thisDog, int count); // variable
-(Void)SetBark:( Void (^) (Dog * thisDog, int count) eachBark; // This function is exposed externally and assigned to people.
. M
-(Void) updatatime :( id) arg
{
If (BarkCallblack)
{
BarkCallback (self, barkCount );
}
}
-(Void) setBark :( void (^) (Dog * thisDog, int count) eachBark
{
[BarkCallblack release];
BarkCallblack = [eachBark copy]; // copy is because the setDog function may be released.
}
-(Void) dealloc
{
[BarkCallblack release];
[Super dealloc];
}
Persons:
In the setDog function:
[_ Dog setBark: ^ (Dog * thisDog, int count ){
NSLog (@ "person dog % d count % d \ n", thisDog. ID, count );
}]