Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
621 views
in Technique[技术] by (71.8m points)

ios - Swift: Using protocol extension results in "unrecognized selector sent to instance"

I'm trying to add a on-tap functionality to all UIViewControllers where they conform to protocol MyProtocol.

Below is how i'm doing it:

import UIKit

protocol MyProtocol: class{
    var foo: String? {get set}
    func bar()
}


extension MyProtocol where Self: UIViewController {
    func bar() {
        print(foo)
    }
}


class TestViewController: UIViewController, MyProtocol{
    var foo: String?

    override func viewDidLoad() {
        super.viewDidLoad()

        foo = "testing"
        let tapGesture = UITapGestureRecognizer(target: self, action: "bar")
}

Which results in following when screen is tapped:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: unrecognized selector sent to instance

I understand the error but don't know how to fix it. Can anyone suggest how this can be done?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that Objective-C knows nothing of protocol extensions. Thus, you cannot use a protocol extension to inject a method into a class in such a way that Objective-C's messaging mechanism can see it. You need to declare bar in the view controller class itself.

(I realize that this is precisely what you were trying to avoid doing, but I can't help that.)

A sort of workaround might be this:

override func viewDidLoad() {
    super.viewDidLoad()

    foo = "testing"
    let tapGesture = UITapGestureRecognizer(target: self, action: "baz")
    self.view.addGestureRecognizer(tapGesture)
}

func baz() {
    self.bar()
}

We are now using Objective-C's messaging mechanism to call baz and then Swift's messaging mechanism to call bar, and of course that works. I realize it isn't as clean as what you had in mind, but at least now the implementation of bar can live in the protocol extension.

(Of course, another solution would be to do what we did before protocol extensions existed: make all your view controllers inherit from some common custom UIViewController subclass containing bar.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...