How to make `NSViewController` a `@MainActor` and have it implement `NSMenuItemValidation`

176 Views Asked by At

I've a custom NSViewController subclass that implements the NSMenuItemValidation protocol. That works just fine, until I mark the view controller as @MainActor.

I believed Apple marked all view controllers as main actor isolated already, but maybe it does so only on iOS. But I thought it would be safe to mark my subclass as such.

Once I add the @MainActor line, I get the warning Instance method 'validateMenuItem' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'NSMenuItemValidation':

@MainActor
final class MyViewController: NSViewController, NSMenuItemValidation {
    func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
    }
}

Is it not okay to mark a custom NSViewController subclass as @MainActor? Or how should I deal with this warning?

I want to mark my view controller, because it needs to co-operate with other classes that are (explicitly) isolated to the main actor and I want to avoid various async boundaries that are totally not necessary, knowing the view controller will always run on the main thread.

1

There are 1 best solutions below

1
Andrew Kestler On

You must mark the function w/ nonisolated. I'm assuming this is because the NSMenuItemValidation protocol is not restricted to the main queue.

nonisolated func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { }