-
Notifications
You must be signed in to change notification settings - Fork 1
/
Dispatch+Convenience.m
102 lines (75 loc) · 1.96 KB
/
Dispatch+Convenience.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// Dispatch+Convenience.m
// Sleep Diary
//
// Created by Alexander Ivanov on 16.10.16.
// Copyright © 2016 Alexander Ivanov. All rights reserved.
//
#import "Dispatch+Convenience.h"
@implementation GCD {
dispatch_semaphore_t _sema;
}
- (instancetype)initWithCount:(NSInteger)count {
self = [self init];
if (self)
_sema = dispatch_semaphore_create(count);
return self;
}
/*
- (void)dealloc {
dispatch_release(_sema);
}
*/
- (BOOL)signal {
return dispatch_semaphore_signal(_sema) == 0;
}
- (BOOL)wait:(NSTimeInterval)time {
return time < 0.0 ? NO : dispatch_semaphore_wait(_sema, time > 0.0 ? dispatch_time(DISPATCH_TIME_NOW, time * NSEC_PER_SEC) : DISPATCH_TIME_FOREVER) == 0;
}
- (BOOL)wait {
return [self wait:0.0];
}
+ (instancetype)new {
return [[self alloc] initWithCount:0];
}
+ (void)sync:(void (^)(GCD *))sync wait:(NSTimeInterval)time {
if (!sync)
return;
GCD *sema = time < 0.0 ? Nil : [GCD new];
sync(sema);
[sema wait:time];
}
+ (void)sync:(void (^)(GCD *))sync {
[self sync:sync wait:0.0];
}
+ (void)queue:(dispatch_queue_t)queue after:(NSTimeInterval)after block:(void (^)(void))block {
if (queue) {
if (after > 0.0)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(after * NSEC_PER_SEC)), queue, block);
else
dispatch_async(queue, block);
} else {
if (after > 0.0)
[NSThread sleepForTimeInterval:after];
block();
}
}
+ (void)global:(void (^)(void))block {
[self queue:GCD_GLOBAL after:0.0 block:block];
}
+ (void)main:(void (^)(void))block {
[self queue:GCD_MAIN after:0.0 block:block];
}
+ (void)once:(void (^)(void))block {
static dispatch_once_t predicate;
dispatch_once(&predicate, block);
}
+ (BOOL)wait:(NSTimeInterval)interval flag:(BOOL *)flag step:(NSTimeInterval)step {
for (; interval > 0.0 && !*flag; interval -= step)
[NSThread sleepForTimeInterval:step];
return *flag;
}
+ (BOOL)wait:(NSTimeInterval)interval flag:(BOOL *)flag {
return [self wait:interval flag:flag step:1.0];
}
@end