What are blocks?
Why should we use blocks?
How does GCD help iOS development?
packages of code that usually appear in the form of methods in Objective-C.
first-class objects
void (^helloWorldBlock)(void) = ^ {
printf ("Hello, World!\n");
};
void (^helloWorldBlock)(void) = ^ {
printf ("Hello, World!\n");
};
helloWorldBlock();
Blocks return just like functions.
int (^fortyTwo)(void) = ^{
return 42;
}
int a = fortyTwo();
Just like functions:
BOOL (^isFortyTwo)(int) = ^(int a) {
return (a == 42);
}
BOOL myBool = isFortyTwo(5); // NO
int a = 42;
void (^myBlock)(void) = ^{
printf("a = %d\n", a);
};
myBlock();
int a = 42;
void (^myBlock)(void) = ^{
a++;
printf("a = %d\n", a);
};
myBlock();
__block int a = 42;
void (^myBlock)(void) = ^{
a++;
printf("a = %d\n", a);
};
myBlock();
Simple block that returns an int and takes a float:
typedef int (^floatToIntBlock)(float);
Now initialize it:
floatToIntBlock foo = ^(float a) { return (int)a; };
First typedef the block, then use it as an argument:
typedef int (^floatToIntBlock)(float);
void useMyBlock(floatToIntBlock foo);
Intro to Grand Central Dispatch
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_Q UEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
[self performLongTask];
}
dispatch_async(queue, block);
dispatch_async_f(queue, context, func);
Schedules block or function on queue, returns immediately
dispatch_sync(queue, block);
dispatch_sync_f(queue, context, func);
Schedules block or function on queue, blocks until completion
dispatch_get_global_queue(priority, flags);
priority is one of three constants:
second arg should always be 0ul (for now)
dispatch_queue_create(label, attr)
Use reverse DNS for label
com.example.myQueue
pass NULL for attr
Be sure to use dispatch_release()