Skip to content

Instantly share code, notes, and snippets.

@GanZhiXiong
Last active December 14, 2023 07:38
Show Gist options
  • Save GanZhiXiong/a4b1ac54e6820f360107a9e9649d1642 to your computer and use it in GitHub Desktop.
Save GanZhiXiong/a4b1ac54e6820f360107a9e9649d1642 to your computer and use it in GitHub Desktop.
Swift Async Block UI
//
// UpdateViewDemo.swift
// MacOSDemoSwiftUI
//
// Created by ganzhixiong on 2023/12/14.
//
import SwiftUI
struct UpdateViewDemo: View {
@StateObject private var myObject = MyObject1(boolValue: true, intValue: 10, stringValue: "Hello", dog: Dog(name: "Fido", age: 3))
func testForInAsync() async {
print("start for \(Thread.current)")
for i in 1...1000_000 {
// print(i)
}
print("end for \(Thread.current)")
}
var body: some View {
VStack {
MillisecondsClockView()
Button("for 100万 in async") {
print("myObject.intValue += 1")
Task.detached {
print("start testForInAsync() \(Thread.current)")
await testForInAsync()
print("end testForInAsync() \(Thread.current)")
}
}
Button("for 100万 in global") {
print("myObject.intValue += 1")
// 创建一个后台队列 (Background Queue)
let queue = DispatchQueue.global(qos: .background)
queue.async {
print("start queue.async \(Thread.current)")
for i in 1...1000_000 {
}
}
}
}
}
}
struct MillisecondsClockView: View {
@State private var currentTime = Date()
var body: some View {
VStack {
Text(getTimeString())
.font(.largeTitle)
.padding()
// Spacer()
}
.onAppear {
startTimer()
}
}
func startTimer() {
let timer = Timer.scheduledTimer(withTimeInterval: 1/60, repeats: true) { timer in
currentTime = Date()
// print(getTimeString())
}
RunLoop.current.add(timer, forMode: .common)
}
func getTimeString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSS"
return formatter.string(from: currentTime)
}
}
class Dog: ObservableObject {
@Published var name: String
@Published var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class MyObject1: ObservableObject {
@Published var boolValue: Bool
@Published var intValue: Int
@Published var intValue1: Int
@Published var stringValue: String
@Published var dog: Dog
init(boolValue: Bool, intValue: Int, stringValue: String, dog: Dog) {
self.boolValue = boolValue
self.intValue = intValue
self.stringValue = stringValue
self.dog = dog
self.intValue1 = intValue
}
}
#Preview {
UpdateViewDemo()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment