回答編集履歴
1
sample
answer
CHANGED
|
@@ -1,1 +1,40 @@
|
|
|
1
|
-
別スレッドで実行して、10秒後にスレッドごと削除してしまうとか。
|
|
1
|
+
別スレッドで実行して、10秒後にスレッドごと削除してしまうとか。
|
|
2
|
+
|
|
3
|
+
【追記】
|
|
4
|
+
|
|
5
|
+
あまり深く考えずに作ったので参考程度に。
|
|
6
|
+
|
|
7
|
+
```swift
|
|
8
|
+
print("[main]", Thread.current)
|
|
9
|
+
let thread = Thread(target: self, selector: #selector(hoge), object: nil)
|
|
10
|
+
thread.start()
|
|
11
|
+
print("start")
|
|
12
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
|
|
13
|
+
print("cancel")
|
|
14
|
+
thread.cancel()
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@objc func hoge() {
|
|
18
|
+
print("[hoge]", Thread.current)
|
|
19
|
+
while true {
|
|
20
|
+
print("thread =", Thread.current, Date())
|
|
21
|
+
if Thread.current.isCancelled {
|
|
22
|
+
print("exit")
|
|
23
|
+
Thread.exit()
|
|
24
|
+
}
|
|
25
|
+
Thread.sleep(forTimeInterval: 3)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
[main] <NSThread: 0x17e64da0>{number = 1, name = main}
|
|
32
|
+
[hoge] <NSThread: 0x17e87010>{number = 3, name = (null)}
|
|
33
|
+
start
|
|
34
|
+
2018-02-28 09:01:08 +0000
|
|
35
|
+
2018-02-28 09:01:11 +0000
|
|
36
|
+
2018-02-28 09:01:14 +0000
|
|
37
|
+
2018-02-28 09:01:17 +0000
|
|
38
|
+
cancel
|
|
39
|
+
exit
|
|
40
|
+
```
|