I have a class named Person, Which is annotated with @MainActor. But as I try to create an instance of this mainactor class it gives an error.
"Call to main actor-isolated initializer 'init(firstName:lastName:)' in a synchronous nonisolated context".
@MainActor
class Person {
var firstName: String = ""
var lastName: String = ""
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
func tryToPrintNameOnMainThread() {
print("Is Main Thread: \(Thread.isMainThread)")
print("\(firstName) \(lastName)")
}
}
class AsyncAwaitViewModel {
let personActor = Person(firstName: "", lastName: "") // Error
let someTestLabel = UILabel() // No Error
}
But if I create UILabel() instance it works. Where UILabel is also a @MainActor annotated class.
My question is why i am seeing this error and what should be ideal way to have @MainActor class instance in this type of scenario.
Creating the Person instance from @MainActor annotated UIViewController subclass works fine.
@MainActor
annotated type or property did not route throughawait MainActor.run(body: { label.text = "dada" })
. Is the article i linked is saying otherwise. Thanks you for patiently going through my queries. – Weinhardt