回答編集履歴

1

sample

2018/02/28 09:02

投稿

fuzzball
fuzzball

スコア16731

test CHANGED
@@ -1 +1,79 @@
1
1
  別スレッドで実行して、10秒後にスレッドごと削除してしまうとか。
2
+
3
+
4
+
5
+ 【追記】
6
+
7
+
8
+
9
+ あまり深く考えずに作ったので参考程度に。
10
+
11
+
12
+
13
+ ```swift
14
+
15
+ print("[main]", Thread.current)
16
+
17
+ let thread = Thread(target: self, selector: #selector(hoge), object: nil)
18
+
19
+ thread.start()
20
+
21
+ print("start")
22
+
23
+ DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
24
+
25
+ print("cancel")
26
+
27
+ thread.cancel()
28
+
29
+ }
30
+
31
+
32
+
33
+ @objc func hoge() {
34
+
35
+ print("[hoge]", Thread.current)
36
+
37
+ while true {
38
+
39
+ print("thread =", Thread.current, Date())
40
+
41
+ if Thread.current.isCancelled {
42
+
43
+ print("exit")
44
+
45
+ Thread.exit()
46
+
47
+ }
48
+
49
+ Thread.sleep(forTimeInterval: 3)
50
+
51
+ }
52
+
53
+ }
54
+
55
+ ```
56
+
57
+
58
+
59
+ ```
60
+
61
+ [main] <NSThread: 0x17e64da0>{number = 1, name = main}
62
+
63
+ [hoge] <NSThread: 0x17e87010>{number = 3, name = (null)}
64
+
65
+ start
66
+
67
+ 2018-02-28 09:01:08 +0000
68
+
69
+ 2018-02-28 09:01:11 +0000
70
+
71
+ 2018-02-28 09:01:14 +0000
72
+
73
+ 2018-02-28 09:01:17 +0000
74
+
75
+ cancel
76
+
77
+ exit
78
+
79
+ ```