iOS. Приемы программирования
Шрифт:
com.pixolity.GCD.serialQueue1
com.pixolity.GCD.serialQueue2
После того как последовательная очередь будет готова, можно приступать к диспетчеризации задач в эту очередь, пользуясь различными функциями GCD, изученными в этой книге.
Пожалуй, самое время для примера. Вот он!
— (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
dispatch_queue_t firstSerialQueue =
dispatch_queue_create(«com.pixolity.GCD.serialQueue1», 0);
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"First iteration, counter = %lu", (unsigned long)counter);
}
});
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Second iteration, counter = %lu", (unsigned long)counter);
}
});
dispatch_async(firstSerialQueue, ^{
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Third iteration, counter = %lu", (unsigned long)counter);
}
});
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
Запустив
First iteration, counter = 0
First iteration, counter = 1
First iteration, counter = 2
First iteration, counter = 3
First iteration, counter = 4
Second iteration, counter = 0
Second iteration, counter = 1
Second iteration, counter = 2
Second iteration, counter = 3
Second iteration, counter = 4
Third iteration, counter = 0
Third iteration, counter = 1
Third iteration, counter = 2
Third iteration, counter = 3
Third iteration, counter = 4
Очевидно, что, хотя мы и направляли блоковые объекты в последовательную очередь асинхронно, очередь выполняла
их код в порядке «первым пришел — первым обслужен». Мы можем изменить этот пример с кодом так, чтобы пользоваться функцией dispatch_async_f вместо dispatch_async:void firstIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"First iteration, counter = %lu", (unsigned long)counter);
}
}
void secondIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Second iteration, counter = %lu", (unsigned long)counter);
}
}
void thirdIteration(void *paramContext){
NSUInteger counter = 0;
for (counter = 0;
counter < 5;
counter++){
NSLog(@"Third iteration, counter = %lu", (unsigned long)counter);
}
}
— (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
dispatch_queue_t firstSerialQueue =
dispatch_queue_create(«com.pixolity.GCD.serialQueue1», 0);
dispatch_async_f(firstSerialQueue, NULL, firstIteration);
dispatch_async_f(firstSerialQueue, NULL, secondIteration);
dispatch_async_f(firstSerialQueue, NULL, thirdIteration);
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}
7.11. Синхронное выполнение задач с помощью операций
Постановка задачи
Необходимо синхронно выполнить серию задач.
Решение
Создавайте операции и запускайте их вручную:
@interface AppDelegate
@property (nonatomic, strong) NSInvocationOperation *simpleOperation;
@end
Реализация делегата приложения такова:
— (void) simpleOperationEntry:(id)paramObject{
Поделиться с друзьями: