Аргумент #selector не относится к методу, свойству или инициализатору @objc - PullRequest
0 голосов
/ 14 марта 2019

Ниже приведен мой код. Я слежу за онлайн-учебником, но получаю вышеуказанную ошибку.

import UIKit
import MultipeerConnectivity

class ViewController: UIViewController, MCBrowserViewControllerDelegate {



    @IBOutlet var xField: [MyImageView]!

    var appDelegate:AppDelegate!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        appDelegate = UIApplication.shared.delegate as? AppDelegate
        appDelegate.mpcHandling.gettingPeerConnection(displayName: UIDevice.current.name)
        appDelegate.mpcHandling.gettingSession()
        appDelegate.mpcHandling.showingSelf(show: true)

        //handling peer state notification

        //getting error for the below mentioned line

        NotificationCenter.default.addObserver(self, selector: #selector("peerChangedNotification:"), name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil)

        NotificationCenter.default.addObserver(self, selector: Selector("handleReceivedNotification:"), name: NSNotification.Name(rawValue: "MPC_DidReceiveNotification"), object: nil)

        mainLogicField()

    }

    @objc func peerChangedNotification(notification:NSNotification){
        let userInfo = NSDictionary(dictionary: notification.userInfo!)

        let state = userInfo.object(forKey: "state") as! Int

        if state != MCSessionState.connecting.rawValue{
            //Now we inform user that we have connected
            self.navigationItem.title = "Connected Successfully"
        }
    }


    @IBAction func getConnected(_ sender: Any) {

        if appDelegate.mpcHandling.gameSession != nil {
            appDelegate.mpcHandling.gettingBrowser()
            appDelegate.mpcHandling.browser.delegate = self

            self.present(appDelegate.mpcHandling.browser, animated: true, completion: nil
            )

        }

    }




    func mainLogicField() {
        for index in 0 ... xField.count - 1 {

            let recognizeGestureTouch = UITapGestureRecognizer(target: self, action: "fieldTapped")

            recognizeGestureTouch.numberOfTapsRequired = 1

            xField[index].addGestureRecognizer(recognizeGestureTouch)
        }
    }

    func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
        appDelegate.mpcHandling.browser.dismiss(animated: true, completion: nil)
    }

    func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
        appDelegate.mpcHandling.browser.dismiss(animated: true, completion: nil)
    }

}

Не уверен, что не так, поскольку я также использовал #selector и @objc для своей функции. Онлайн-учебник только что использовал NotificationCenter.default.addObserver (self, селектор: "peerChangedNotification:", имя: NSNotification.Name (rawValue: "MPC_DidChangeStateNotification"), объект: nil) без добавления #selector, но если я удаляю #selector, то выдает предупреждение «Нет метода, объявленного с помощью селектора Objective C 'peerChangedNotification'". Я пытаюсь подключить 2 устройства с помощью mutipeer

1 Ответ

0 голосов
/ 14 марта 2019

Selector (): Получает строку / строковый литерал в качестве параметра.Он использовался ранее, и #selector является обновленным определением.

# селектор: Вы пытаетесь передать строку в #selector, тогда как для этого требуется ссылка на функцию типа Objective-C.Правильный пример:

NotificationCenter.default.addObserver(self, selector: #selector(peerChangedNotification(notification:)), name: NSNotification.Name("MPC_DidChangeStateNotification"), object: nil)
...