-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSteadilyTrackingOptimizer.m
101 lines (91 loc) · 2.66 KB
/
SteadilyTrackingOptimizer.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
//
// SteadilyTrackingHelper.m
// Face_meal
//
// Created by 沙少盼 on 2017/11/6.
// Copyright © 2017年 fu. All rights reserved.
//
#import "SteadilyTrackingOptimizer.h"
#define DEFULT_MAX_QUEUE_COUNT 100
@interface SteadilyTrackingOptimizer ()
{
CFRunLoopRef _runloop;
CFRunLoopObserverRef _runloopO;
}
@property (nonatomic,copy)NSMutableDictionary *tasks;
//@property (nonatomic,strong)NSTimer *timer;
@end
@implementation SteadilyTrackingOptimizer
- (instancetype)init{
if (self = [super init]) {
// _timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(runloopTimer) userInfo:nil repeats:YES];
[self initObserver];
}
return self;
}
//- (void)runloopTimer{}
- (NSMutableDictionary *)tasks{
if (!_tasks) {
_tasks = @{}.mutableCopy;
}
return _tasks;
}
- (void)addTaskInTime:(CFRunLoopActivity)activity
maxQueue:(NSUInteger)maxQueue
isTracking:(BOOL)isTrcking
task:(taskBlock)task{
NSMutableArray *tasks = [self.tasks objectForKey:@(activity)];
if (!tasks) {
tasks = @[].mutableCopy;
}
[tasks addObject:task];
if (isTrcking && tasks.count > (maxQueue ? maxQueue : DEFULT_MAX_QUEUE_COUNT)) {
[tasks removeObjectAtIndex:0];
}
[self.tasks setObject:tasks forKey:@(activity)];
}
static void CallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
SteadilyTrackingOptimizer *optimizer = (__bridge SteadilyTrackingOptimizer *)info;
NSMutableArray *tasks = [optimizer.tasks objectForKey:@(activity)];
if (tasks.count == 0) {
return;
}
taskBlock task = tasks.firstObject;
if (task) {
task();
[tasks removeObject:task];
[optimizer.tasks setObject:tasks forKey:@(activity)];
}
}
- (void)initObserver{
//拿到当前runloop
CFRunLoopRef runloop = CFRunLoopGetCurrent();
_runloop = runloop;
//定义一个观察者
static CFRunLoopObserverRef defultModeO;
//定义一个上下文
CFRunLoopObserverContext context = {
0,
(__bridge void *)(self),
&CFRetain,
&CFRelease,
NULL
};
defultModeO = CFRunLoopObserverCreate(NULL, kCFRunLoopAllActivities, YES, 0, &CallBack, &context);
_runloopO = defultModeO;
}
- (void)addOptimizer{
//添加观察者
if (!_runloopO || !_runloop) {
[self initObserver];
}
CFRunLoopAddObserver(_runloop, _runloopO, kCFRunLoopCommonModes);
}
- (void)removeOptimizer{
//移除观察者
CFRunLoopRemoveObserver(_runloop, _runloopO, kCFRunLoopCommonModes);
}
- (void)dealloc{
NSLog(@"Optimizer dealloc");
}
@end