首页 > 代码库 > IOS GCD
IOS GCD
UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[btn setTitle:@"default"forState:UIControlStateNormal];
btn.backgroundColor = [UIColorblackColor];
[self.view addSubview:btn];
//情况一
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for( NSInteger i = 0; i < 20; ++ i )
{
sleep(1);
NSLog(@"loop:%d",i);
dispatch_async(dispatch_get_main_queue(), ^{
NSString * str = [NSString stringWithFormat:@"%d",i];
[btn setTitle:str forState:UIControlStateNormal];
});
}
});
//情况二
/*
dispatch_queue_t serQ = dispatch_queue_create("rock", DISPATCH_QUEUE_SERIAL);
dispatch_async(serQ, ^{
for( NSInteger i = 0; i < 20; ++ i )
{
sleep(1);
NSLog(@"loop:%d",i);
dispatch_async(dispatch_get_main_queue(), ^{
NSString * str = [NSString stringWithFormat:@"%d",i];
[btn setTitle:str forState:UIControlStateNormal];
});
}
});
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
当某几个任务执行完毕之后,接着执行另外一个任务,那就应该使用dispatch group 这个功能了
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
for( NSInteger i = 0; i < 10; ++ i )
{
sleep(1);
NSLog(@"loop1:%d",i);
}
});
dispatch_group_async(group,dispatch_get_global_queue(0, 0),^{
for( NSInteger i = 0; i < 10; ++ i )
{
sleep(1);
NSLog(@"loop2:%d",i);
}
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"done");
});