grand central dispatch
Introduction
-
Blocks
What are blocks?
Why should we use blocks?
-
Grand Central Dispatch
How does GCD help iOS development?
BLOCKS
packages of code that usually appear in the form of methods in Objective-C.
first-class objects
Your First Block
void (^helloWorldBlock)(void) = ^ {
printf ("Hello, World!\n");
};
calling your first block
void (^helloWorldBlock)(void) = ^ {
printf ("Hello, World!\n");
};
helloWorldBlock();
block that return
Blocks return just like functions.
int (^fortyTwo)(void) = ^{
return 42;
}
int a = fortyTwo();
block that take arguments
Just like functions:
BOOL (^isFortyTwo)(int) = ^(int a) {
return (a == 42);
}
BOOL myBool = isFortyTwo(5); // NO
block capture scope
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();
Block typedef
Simple block that returns an int and takes a float:
typedef int (^floatToIntBlock)(float);
Now initialize it:
floatToIntBlock foo = ^(float a) { return (int)a; };
Using blocks as arguments
- Method Signature:
-
- (void)doThisBlock:(void (^)(id obj))block
- returns void, takes id argument
block typedef as arguments
First typedef the block, then use it as an argument:
typedef int (^floatToIntBlock)(float);
void useMyBlock(floatToIntBlock foo);
Intro to Grand Central Dispatch
grand central dispatch
-
Open-source threading library (dispatch)
-
dispatch tasks to multiple cores
-
Automatically optimizes threading
Simple GCD
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_Q UEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
[self performLongTask];
}
basic dispatch function
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 quesues
- dispatch_queue_t
- Main Queue
- Analogous to main thread (Do your UI operations here)
- dispatch_get_main_queue()
global queues
dispatch_get_global_queue(priority, flags);
priority is one of three constants:
- DISPATCH_QUEUE_PRIORITY_LOW
- DISPATCH_QUEUE_PRIORITY_NORMAL
- DISPATCH_QUEUE_PRIORITY_HIGH
second arg should always be 0ul (for now)
Making queues
dispatch_queue_create(label, attr)
Use reverse DNS for label
com.example.myQueue
pass NULL for attr
Be sure to use dispatch_release()
Using queues
- Custom queues are serial
- First-in, first-out, one at a time
- Global queues are concurrent
- GCD automatically chooses how many (usually # of CPU cores)
grand central dispatch
By Torry Harris Business Solutions
grand central dispatch
- 1,146