-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWGRunLoopVC.m
More file actions
99 lines (85 loc) · 2.77 KB
/
WGRunLoopVC.m
File metadata and controls
99 lines (85 loc) · 2.77 KB
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
//
// WGRunLoopVC.m
// WGFcodeNotes
//
// Created by wubaicai on 2020/9/9.
// Copyright © 2020 WG. All rights reserved.
//
#import "WGRunLoopVC.h"
#import "WGThread.h"
#import "WGRunLoopSecondVC.h"
#import "WGProxy.h"
@interface WGRunLoopVC ()
@property(nonatomic, strong) WGThread *thread;
@property(nonatomic, strong) NSPort *port;
@property(nonatomic, assign) BOOL stopRunLoop;
@end
@implementation WGRunLoopVC
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
_port = [NSMachPort port];
self.stopRunLoop = NO;
_thread = [[WGThread alloc]initWithTarget:self selector:@selector(threadTest) object:nil];
[_thread start];
}
-(void)threadTest {
NSLog(@"当前子线程开始执行任务");
@autoreleasepool {
NSRunLoop *currentThreadRunLoop = [NSRunLoop currentRunLoop];
[currentThreadRunLoop addPort:_port forMode:NSRunLoopCommonModes];
[self addObserverForCurrentRunloop];
[self performSelector:@selector(removeThread) withObject:nil afterDelay:10.0];
while (!self.stopRunLoop) {
[currentThreadRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
};
NSLog(@"========");
}
}
-(void)removeThread {
NSLog(@"---%s---",__func__);
_stopRunLoop = YES;
CFRunLoopStop(CFRunLoopGetCurrent());
}
// 验证子线程并没有销毁
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self performSelector:@selector(threadTask) onThread:self.thread withObject:nil waitUntilDone:NO];
}
-(void)threadTask {
NSLog(@"在保活的线程下执行了任务");
}
-(void)dealloc {
NSLog(@"页面销毁了");
}
-(void)addObserverForCurrentRunloop {
CFRunLoopObserverContext context = { 0, (__bridge void *)(self), NULL, NULL };
CFRunLoopObserverRef observer = CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopAllActivities, YES, 0, &runLoopCallBack, &context);
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopCommonModes);
}
static void runLoopCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
NSString *str;
switch (activity) {
case kCFRunLoopEntry:
str = @"Entry";
break;
case kCFRunLoopBeforeTimers:
str = @"BeforeTimers";
break;
case kCFRunLoopBeforeSources:
str = @"BeforeSources";
break;
case kCFRunLoopBeforeWaiting:
str = @"BeforeWaiting";
break;
case kCFRunLoopAfterWaiting:
str = @"AfterWaiting";
break;
case kCFRunLoopExit:
str = @"Exit";
break;
default:
break;
}
NSLog(@"current RunLoop activity: %@",str);
}
@end