Bird
0
0

Why does this code cause a runtime crash when the button is tapped?

medium📝 Debug Q7 of 15
iOS Swift - SwiftUI Basics
Why does this code cause a runtime crash when the button is tapped?
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)

@objc func buttonPressed() {
  print("Pressed")
}
AThe method is missing the @IBAction keyword.
BThe button is not enabled by default.
CThe selector expects a method with a sender parameter, but buttonPressed has none.
DThe button is not added to the view hierarchy.
Step-by-Step Solution
Solution:
  1. Step 1: Match selector signature

    The selector #selector(buttonPressed(_:)) expects a method with one parameter (sender).
  2. Step 2: Check method signature

    The method buttonPressed() has no parameters, causing a mismatch and runtime crash.
  3. Final Answer:

    The selector expects a method with a sender parameter, but buttonPressed has none. -> Option C
  4. Quick Check:

    Selector and method signature must match [OK]
Quick Trick: Selector signature must match method parameters exactly [OK]
Common Mistakes:
  • Omitting sender parameter when selector expects it
  • Assuming @IBAction is required for selectors
  • Ignoring method signature mismatch

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes