SwiftUI中CoreData实体StudentData调用chapter属性导致应用崩溃问题求助
Hey Paolo, let's break down why your app is crashing and fix it step by step!
崩溃原因分析
The error '-[StudentData chapter]: unrecognized selector sent to instance' tells us one key thing: your Core Data StudentData entity doesn't actually have a chapter property available at runtime, or there's a mismatch between the property name in your Core Data model and your Swift code.
Core Data uses Key-Value Coding (KVC) to access properties, so if the chapter property doesn't exist in the underlying model (or the name/spelling is off), it can't find the method to get that value and crashes.
Step 1: Verify your Core Data Model
First, open your .xcdatamodeld file and check the StudentData entity:
- Make sure there’s a property named exactly
chapter(check for typos, capitalization, or pluralization errors—likeChapterorchapterswon’t match your code) - Confirm the property’s type matches what you’re using in code (you’re treating it as an optional String, so the model should have a String attribute marked as optional)
Step 2: Sync Core Data Code with Model
If the model has the chapter property but your code still crashes, your generated StudentData class is out of sync with the model:
- Open the
.xcdatamodeldfile, select theStudentDataentity - In the right-hand inspector, check the Codegen setting:
- If it’s set to
Class Definition, clean your project (Cmd+Shift+K) and rebuild—sometimes Xcode doesn’t update the generated code automatically - If you’re using manual code generation, delete your existing
StudentData.swiftfile, then go toEditor > Create NSManagedObject Subclass...to regenerate it from the model
- If it’s set to
Step 3: Fix the NavigationLink Parameter
There’s another bug in your StudentView that will cause problems even after fixing the crash:
Your current NavigationLink passes a new empty StudentData() instance instead of the actual selected student:
NavigationLink(destination: DetailView(myStudent:selectedStudent)) { Text("More Details") }
Change this to pass the myStudent variable (the one you’re already displaying):
NavigationLink(destination: DetailView(myStudent: myStudent)) { Text("More Details") }
This ensures DetailView loads the correct student’s data instead of an empty placeholder.
Final Checks
After making these changes:
- Clean your project (
Cmd+Shift+K) - Delete the app from your simulator/device (to clear old Core Data persistent stores that might have outdated schema)
- Rebuild and run
This should resolve the crash and get your DetailView working as expected!
内容的提问来源于stack exchange,提问作者Paolo Farina

