2016-03-22 14 views
7

che sto cercando di risolvere il mio NSNotificationCenter e la sua non funzionasintassi "Selector" Swift 2.2

il messaggio:

'Use of string literal for Objective-C selectors is deprecated; use '#selector' instead'. 

la linea:

NSNotificationCenter.defaultCenter().addObserver(self, Selector :#selector(GameViewController.goBack)(GameViewController.goBack), object: nil) 
     self.dismissViewControllerAnimated(true, completion: { 
     }); 
     } 

risposta

16

@ risposta di Eendje è corretto da il suo primo commento.

Penso che sia la risposta migliore.

NSNotificationCenter.defaultCenter().addObserver(self, #selector(self.goBack), name: "your notification name", object: nil) 

Se alcune azioni ha bersaglio, dovrebbe essere presentato come #selector(target.method) o #selector(target.method(_:))

Ecco un altro esempio

UIGestureRecognizer(target: target action:#selector(target.handleGesture(_:)) 
-2

Aggiungi @objc al tuo metodo di selezione:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "YOUR_SELECTOR_METHOD:", name: "your notification name", object: nil) 

@objc func YOUR_SELECTOR_METHOD(notification: NSNotification) { 
//your code 
} 
+0

Questo è un brutto modo di fare le cose. Solo perché puoi farlo, non significa che dovresti. Il modo meno incline all'errore è usare '# selector' – barndog

8

Il codice incollato non ha alcun senso:

Selector :#selector(GameViewController.goBack)(GameViewController.goBack) // ??? 

Dovrebbe essere:

NSNotificationCenter.defaultCenter().addObserver(self, #selector(goBack), name: "your notification name", object: nil) 
+0

Anche questo non è corretto.Stai aggiungendo un osservatore, 'self', ma passando in una classe o funzione di livello statico' goBack'. Per ottenere un riferimento a una funzione di istanza come 'addSubview' su' UIView', devi fare 'let view = UIView()' 'let functionVariable = view.addSubview (_ :)' – barndog

+1

e il parametro NSNotification con il selettore ? È ancora (_ :)? –

4

Bisogna guardare a questo: https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

La #selector proposta è stata fatta in collaborazione con un'altra proposta, specificando le funzioni veloci da loro etichette di argomento. Quindi, se ho una struct:

struct Thing 
    func doThis(this: Int, withOtherThing otherThing: Int) { 

    } 
} 

vorrei riferire che funzione come:

let thing = Thing() 
thing.doThis(_:withOtherThing:) 

Resta qui sto riferimento alla funzione stessa, non chiamarla.

Si potrebbe utilizzare quello con #selector:

#selector(self.doThis(_:withOtherThing:) 

funzione senza argomenti:

#selector(self.myFunction) 

Funzione con un argomento implicito:

#selector(self.myOtherFunction(_:)) 
Problemi correlati