Home > Back-end >  Argument type 'AnyObject.Protocol' expected to be an instance of a class or class-constrai
Argument type 'AnyObject.Protocol' expected to be an instance of a class or class-constrai

Time:09-17

In my menu bar macOS app, i want to assign a hotkey where it can show or hide the menu bar popover when a user presses a custom hotkey.

App Delegate

import KeyboardShortcuts
class AppDelegate: NSObject, NSApplicationDelegate, ObservableObject {
    var popover = NSPopover.init()
    var statusBar: StatusBarController?

    func applicationDidFinishLaunching(_ aNotification: Notification) {
       
            KeyboardShortcuts.onKeyUp(for: .triggerPopover, action: {
                self.statusBar?.togglePopover(sender: AnyObject)  
            }). 
    }
        

StatusBarController

class StatusBarController {
    private var statusBar: NSStatusBar
    private var statusItem: NSStatusItem
    private var popover: NSPopover
    
    @objc func togglePopover(sender: AnyObject) {
        if(popover.isShown) {
            hidePopover(sender)
        }
        else {
            showPopover(sender)
        }
    }
    
    func showPopover(_ sender: AnyObject) {
        if let statusBarButton = statusItem.button {
            popover.show(relativeTo: statusBarButton.bounds, of: statusBarButton, preferredEdge: NSRectEdge.maxY)
        }
    }
    
    func hidePopover(_ sender: AnyObject) {
        popover.performClose(sender)
        eventMonitor?.stop()
    }
    
}
    

I want to trigger the togglePopover function from StatusBarController but i'm getting this error

Argument type 'AnyObject.Protocol' expected to be an instance of a class or class-constrained type

CodePudding user response:

You pass protocol to the togglePopover instead of an instance. You can pass self.

func applicationDidFinishLaunching(_ aNotification: Notification) { [weak self] in 
    KeyboardShortcuts.onKeyUp(for: .triggerPopover, action: {
        guard let strongSelf = self else { return }
        strongSelf.statusBar?.togglePopover(sender: strongSelf)  
    })
}

Also, it is better to make self as weak. I understand that AppDelegate and StatusBarController will never be deleted anyway, but it is a good practice.

  • Related