17

I am trying to perform selector with object in swift 3.0

I have a selector which have one parameter

func imageSelected(aImage : UIImage)

and I am calling it like

viewC.perform(Selector.init("imageSelected:"), with: image, afterDelay: 0.1)

But the app crashes with error that the selector is not defined.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
Zaheer Abbas
  • 225
  • 1
  • 2
  • 10

3 Answers3

9

Here's something I always do when I encounter selectors in swift: Ignore the parameters, just use the name.

You used this:

imageSelected:

What is that : doing there? Delete it! Just use the name of the method!

Also, there is this great #selector syntactic sugar, please use that:

viewC.perform(#selector(imageSelected), with: image, afterDelay: 0.1)
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • The synthetic sugar is lovely, but this method contains a bug in Xcode10/macOS 10.13: whatever CGPoint I pass in ends up as (0.0, 9.223372036854776e+18). Just putting this here so save someone else a lot of headaches. The solution is to set a temporary variable and to access it directly in the delayed function. (Other objects passed as parameters seem just fine.) – green_knight Oct 03 '19 at 12:25
7

This is for swift 4.0

perform(#selector(yourMethodHere), with: nil, afterDelay: 1)

Add @objc flag before your function

@objc public func yourMethodHere(){
     //your code here
}
sonali
  • 165
  • 3
  • 9
5

It started working well as, I modified the selector being called

from

func imageSelected(aImage : UIImage)

to this

func imageSelected(_ aImage : UIImage)
Zaheer Abbas
  • 225
  • 1
  • 2
  • 10