Objective-C canceled selector replacement

As has been said recently, literal selectors are out of date. There's a quick fix that works fine if the selector is only in this class.

But consider this example (I have a lot more code, this is a simplified example):

static func createMenuButton(controller:UIViewController) -> UIBarButtonItem { let menuButton = UIButton(frame: CGRectMake(0, 0, 22, 22)) menuButton.addTarget(controller, action: Selector("menuButtonClicked:"), forControlEvents:.TouchUpInside) let menuButtonContainer = UIView(frame: menuButton.frame) menuButtonContainer.addSubview(menuButton) let menuButtonItem = UIBarButtonItem(customView: menuButtonContainer) return menuButtonItem } 

This utility method gives me good functionality that will be used in various view controllers. Due to its multiple use, I would have to copy it to each view controller in order to use the new #selector syntax. But Apple, why is it not recommended to use a more dynamic method? I assume that in the new release they will simply delete it, for example, i++ , i-- and for C-style loops (but they can be easily replaced, although I do not understand why they delete them). Are there any workarounds to support this approach in future releases? Each new release breaks all my project syntaxes.

+1
source share
1 answer

why refuse a more dynamic method?

From the suggestion for this change :

we free the developer from having to do naming transfer manually and statically check if the method exists and is exposed to Objective-C.

For your approach, you can make a protocol indicating the presence of a specific method:

 @objc protocol MenuButtonClickable { func menuButtonClicked() } 

In your view controller add this method:

 extension MyViewController : MenuButtonClickable { func menuButtonClicked() { // do something } } 

Then update your method signature to use this protocol:

 static func createMenuButton(controller:MenuButtonClickable) -> UIBarButtonItem { 

Now the Swift compiler ensures that the controller has this method, so you can use the new #selector syntax.

And if you accidentally try to use this method on a view controller without this function, you will get a compile-time error instead of a run-time error.

+2
source

Source: https://habr.com/ru/post/1245739/


All Articles