Swift: Using protocol extension results in “unrecognized selector sent to instance”

前端 未结 2 876
遥遥无期
遥遥无期 2020-12-12 00:52

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:



        
2条回答
  •  时光说笑
    2020-12-12 01:10

    Matt's answer is correct. You can play in your playground to see exactly how it works. In next snippet you can to see that even though some object can perform objc selector, if not properly used, it could crash your code :-)

    //: Playground - noun: a place where people can play
    import Foundation
    protocol Bar {}
    extension Bar {
        func bar()->Self {
            print("bar from protocol Bar extension")
            dump(self)
            return self
        }
    }
    class C: NSObject {
        func dummy() {
            print("dummy from C")
            dump(self)
        }
    }
    extension NSObject {
        func foo()->NSObject {
            print("foo from NSObject extension")
            dump(self)
            return self
        }
    }
    let c = C()
    c.respondsToSelector("foo")     // true
    c.respondsToSelector("dummy")   // true
    c.foo()
    let i = c.performSelector("foo")// prints the same and DON'T crash
    c.dummy()   // works
    //c.performSelector("dummy")    // if uncommented then
    /* prints as expected
    dummy from C
    ▿ C #0
      - super: <__lldb_expr_517.C: 0x7fcca0c05a60>
    */
    // and crash!!! because performSelector returns Unmanaged!
    // and this is not what we return from dummy ( Void )
    
    let o = NSObject()
    o.foo()
    extension NSObject: Bar {}
    // try to uncomment this extension and see which version is called in following lines
    /*
    extension NSObject {
        func bar() -> Self {
            print("bar implemented in NSObject extension")
            return self
        }
    }
    */
    
    c.bar() // bar protocol extension Bar is called here
    o.bar() // and here
    
    o.respondsToSelector("foo") // true
    o.respondsToSelector("bar") // false as expected ( see matt's answer !! )
    o.performSelector("foo")    // returns Unmanaged(_value: )
    

    There is a big gotcha with performSelector: and friends: it can only be used with arguments and return values that are objects! So if you have something that takes e.g. a boolean or return void you're out of luck.

    I would like to suggest further reading for everybody who use mixture of Swift and ObjectiveC

提交回复
热议问题