代码块只执行一次
(1)创建单例
+ (instancetype)cacher {
static MHPCacher*cacher =nil;
static dispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
cacher = [MHPCachernew];
});
returncacher;
}
(2)防止重复执行代码块,如点击事件
static dispatch_once_t disOnce;
dispatch_once(&disOnce,^ {
if([_delegate respondsToSelector:@selector(rewardDetailHeaderBtnTouchDelegateSelector:)]) {
[_delegate rewardDetailHeaderBtnTouchDelegateSelector:1001];
}
});
延时
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
CHPChildController vc =self.childViewControllers[self.selectedButton.tag-1];
vc.loadPage =1;
[vc requestListData];
});
网络请求队列
dispatch_group_tgroup =dispatch_group_create();
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_group_enter(group);
for(NSMutableDictionary*parameDicinpostArray) {
dispatch_group_async(group, q, ^{
[AFHttp requestWihtMethod:MyRequestMethodTypePost url:@"api/Objects/newPraise" params:parameDic success:^(id response) {
NSLog(@"执行完成%@", parameDic);
//删除对应的数据
NSString*oidStr = [NSStringstringWithFormat:@"%@",parameDic[@"oId"]];
[[MHPCachercacher]clearCacheWith:PraiseTypeAndid:oidStr];
}failure:^(NSError*err) {
}];
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"所有队列完毕 %@", [NSThreadcurrentThread]);
dispatch_group_leave(group);
});
异步加载图片回到主线程刷新UI
__weak __typeof (self)weakSelf = self; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:adModel.sharePic];
weakSelf.shareImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
dispatch_async(dispatch_get_main_queue(), ^{
self.shareImageView.image = weakSelf.shareImage;
});
});
创建定时器
-(void)gcdTimer{
//定义队列
//声明
@property (nonatomic, strong) dispatch_source_t timer;
//创建
-(void)createGCDTimer{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//创建定时器
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
dispatch_time_tstart =DISPATCH_TIME_NOW; //当前时间
dispatch_time_tinterval =1.0*NSEC_PER_SEC; //间隔时间 --秒
//设置定时器
dispatch_source_set_timer(self.timer, start, interval,0);
//设置回调
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"-------%@",[NSThread currentThread]);
[selfcountDownTimerSelector];
});
}
//使用
dispatch_resume(self.timer);