Alexey K Alexey K - 2 months ago 5x
iOS Question

Setting target method of a button to a function from another class

I have a function that fetches photos info from facebook. I try to abstract it by adding it to another class and setting target function of the button to that class function.

So I have a singleton class

class FacebookManager {

static let sharedInstance = FacebookManager()

func getAlbums() {

var request: FBSDKGraphRequest = FBSDKGraphRequest.init(graphPath: "/\(facebookID!)/albums", parameters: ["fields": "cover_photo, name, description"])
request.startWithCompletionHandler({ (connection, result, error) -> Void in
// do stuff


and a method in viewcontroller for button that calls that function

dummyButton?.addTarget(FacebookManager.self, action: Selector("getAlbums"), forControlEvents: .TouchUpInside)

but after tapping on button I get an error

2016-08-17 00:12:21.599 Lovrr[11807:3832289] *** NSForwarding: warning: object 0x10717c888 of class 'app.FacebookManager' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector +[app.FacebookManager getAlbums]

in some topic in stackoverflow I saw an advice of subclassing
in FacebookManager. After doing this I get another error

[app.FacebookManager getAlbums]: unrecognized selector sent to class 0x1047026f0
2016-08-17 00:13:49.469 app[11892:3834005] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[app.FacebookManager getAlbums]: unrecognized selector sent to class 0x1047026f0'

How to do what I want properly ?


Your target is wrong:

dummyButton?.addTarget(FacebookManager.self, action: Selector("getAlbums"), forControlEvents: .TouchUpInside)

FacebookManager.self is static. getAlbums is a class method. => unrecognized selector

Try to change:

dummyButton?.addTarget(FacebookManager.sharedInstance, action: Selector("getAlbums"), forControlEvents: .TouchUpInside)