Xcode9.3.1中UITextView调用becomeFirstResponder崩溃求助
becomeFirstResponder Crash in Xcode 9.3.1 + Swift 4.1 I've run into this exact weird crash before when working with Xcode 9.3.1 and Swift 4.1—calling becomeFirstResponder on a UITextView triggers an EXC_BAD_ACCESS error, with logs showing UI methods being sent to non-UI objects like __NSCFString (receiving isHidden) or __NSArrayI (receiving position). Here's how I fixed it:
Possible Root Cause
This appears to be a UIKit bug specific to this Xcode/Swift version. The crash happens when the UITextView's internal state isn't fully synchronized, leading to wild pointer references that mix up non-UI objects with UI responders in the event chain. Common triggers include calling becomeFirstResponder too early, or having memory issues with attributed text attached to the TextView.
Solutions
1. Quick Workaround: Delay the becomeFirstResponder Call
Give UIKit a tiny window to finish setting up the TextView's internal components by wrapping the call in a delayed main queue dispatch:
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { yourTextView.becomeFirstResponder() }
This is the fastest way to get rid of the crash immediately, though it's a temporary fix.
2. Fix Attributed Text (If Used)
If your TextView uses attributedText, this is often the culprit. Swift 4.1 had some changes in how NSAttributedString is handled, and Xcode 9.3.1's UIKit didn't play nicely with certain custom attributes or improperly constructed attributed strings:
- Test by replacing
attributedTextwith plaintextfirst—if the crash stops, rebuild your attributed string from scratch, avoiding any third-party libraries that aren't updated for Swift 4.1. - Ensure you're not retaining any invalid references in the attributed string's attributes (like stale UI-related objects).
3. Ensure Proper View Hierarchy & Timing
Never call becomeFirstResponder in viewDidLoad—the TextView hasn't been added to the view hierarchy or laid out yet. Move the call to viewDidAppear(_:) instead, where the TextView is fully initialized and visible.
4. Upgrade Xcode (Long-Term Fix)
This bug was fixed in later Xcode versions (starting from Xcode 10+). If your project allows, upgrading to a newer Xcode/Swift version will eliminate the issue entirely without workarounds.
内容的提问来源于stack exchange,提问作者Chrishon Wyllie

