Нахавандипур Вандад
Шрифт:
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{
NSLog(@"Parameter Object = %@", paramObject);
NSLog(@"Main Thread = %@", [NSThread mainThread]);
NSLog(@"Current Thread = %@", [NSThread currentThread]);
}
— (BOOL) application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSNumber *simpleObject = [NSNumber numberWithInteger:123];
self.simpleOperation = [[NSInvocationOperation alloc]
initWithTarget: self
selector:@selector(simpleOperationEntry:)
object: simpleObject];
[self.simpleOperation start];
self.window = [[UIWindow alloc] initWithFrame:
[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];