-
-
Save SatoTakeshiX/c3cb6fe57ff1424931c21d97c5f1496a to your computer and use it in GitHub Desktop.
Task.initでselfを直接参照しても循環参照起こらないことを示すコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// TaskInitViewController.swift | |
// TaskInit | |
// | |
// Created by satoutakeshi on 2022/08/07. | |
// | |
import UIKit | |
class TaskInitViewController: UIViewController { | |
var number: Int = 0 | |
var clouser: () -> () = {} | |
var task: Task<Void, Error>? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
task = Task { | |
print(Date().description) | |
//try await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC) | |
try Task.checkCancellation() | |
await Task.sleep(7 * NSEC_PER_SEC) | |
//try Task.checkCancellation() | |
if Task.isCancelled { | |
// 独自のキャンセル処理 | |
// | |
throw CancellationError() | |
} | |
print(number) | |
print(Date().description) | |
} | |
request { [weak self] in | |
guard let self = self else { return } | |
print(self.number) | |
} | |
} | |
override func viewDidAppear(_ animated: Bool) { | |
super.viewDidAppear(animated) | |
task?.cancel() | |
} | |
func request(completion: @escaping () -> ()) { | |
clouser = completion | |
} | |
func run() { | |
clouser() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
このViewControllerをmodalで表示するコードを作れば動きを確認できます。
参照ブログ
https://blog.personal-factory.com/2022/08/06/not-require-weak-self-in-task-init/
Simulator.Screen.Recording.-.iPhone.12.-.2022-09-22.at.10.59.48.mp4