Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax "Selector" Swift 2.2

Tags:

swift

I'm trying to fix my NSNotificationCenter and its not working

the message :

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

the line :

NSNotificationCenter.defaultCenter().addObserver(self, Selector :#selector(GameViewController.goBack)(GameViewController.goBack), object: nil)
        self.dismissViewControllerAnimated(true, completion: {
        });
        }
like image 567
Omer Harel Avatar asked Mar 22 '16 06:03

Omer Harel


People also ask

How do you write a selector in Swift?

In Swift, Objective-C selectors are represented by the Selector structure, and you create them using the #selector expression. In Swift, you create a selector for an Objective-C method by placing the name of the method within the #selector expression: #selector(MyViewController. tappedButton(_:)) .

What is iOS selector?

A selector is the name used to select a method to execute for an object, or the unique identifier that replaces the name when the source code is compiled. A selector by itself doesn't do anything. It simply identifies a method.

What is perform in Swift?

Sends a specified message to the receiver and returns the result of the message. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Required.


3 Answers

@Eendje's answer is incorrect by its first comment.

I think it is better answer.

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

If some actions has target, it should be presented like #selector(target.method) or #selector(target.method(_:))

Here is another example

UIGestureRecognizer(target: target action:#selector(target.handleGesture(_:))
like image 150
Wanbok Choi Avatar answered Nov 01 '22 10:11

Wanbok Choi


The code you pasted doesn't make any sense:

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

It should be:

NSNotificationCenter.defaultCenter().addObserver(self, #selector(goBack), name: "your notification name", object: nil)
like image 8
Eendje Avatar answered Nov 01 '22 09:11

Eendje


You have to look at this: https://github.com/apple/swift-evolution/blob/master/proposals/0022-objc-selectors.md

The #selector proposal was made in conjunction with another proposal, specifying swift functions by their argument labels. So if I have a struct:

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

    }
}

I would reference that function like:

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

Remember here I'm referencing the function itself, not calling it.

You would use that with #selector:

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

Function with no arguments:

#selector(self.myFunction)

Function with one implicit argument:

#selector(self.myOtherFunction(_:))
like image 4
barndog Avatar answered Nov 01 '22 09:11

barndog