Skip to content

Instantly share code, notes, and snippets.

@SatoTakeshiX
Created September 22, 2022 01:58
Show Gist options
  • Save SatoTakeshiX/c3cb6fe57ff1424931c21d97c5f1496a to your computer and use it in GitHub Desktop.
Save SatoTakeshiX/c3cb6fe57ff1424931c21d97c5f1496a to your computer and use it in GitHub Desktop.
Task.initでselfを直接参照しても循環参照起こらないことを示すコード
//
// 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()
}
}
@SatoTakeshiX
Copy link
Author

SatoTakeshiX commented Sep 22, 2022

この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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment