What's the advantage of #selector update in Swift 2.3?

后端 未结 3 1465
孤城傲影
孤城傲影 2021-01-19 00:53

I can\'t see a problem with just writing the method name as a string. Im just curious as to why this is better?

3条回答
  •  萌比男神i
    2021-01-19 01:32

    This is a huge change. Basically, this closes the biggest crash-hole in the language.

    If you form a Selector as a string literal, and you form it wrong — which is all too easy — or if you form it right but the method in question is not exposed to Objective-C, you will crash at runtime with the dreaded Unrecognized selector console message — the most common crash in both Objective-C and Swift. (Do a Stack Overflow on "unrecognized selector"; you will see what I mean.)

    Now, the #selector syntax means that you will form the Selector using a function reference, which the compiler will check at compile time. If you make a mistake, the compiler stops you dead. If you do it right, the compiler forms the Selector for you — correctly. You don't need to know anything about how to form the Selector string; the compiler does all the work. Thus, your chance of crashing in this way is effectively reduced to zero. The "unrecognized selector" crash is dead as a doornail.

提交回复
热议问题