CodexBloom - Programming Q&A Platform

Crash when using Swift Concurrency with Core Data on iOS 17

šŸ‘€ Views: 1 šŸ’¬ Answers: 1 šŸ“… Created: 2025-07-07
swift core-data ios-17 swift-concurrency

I'm integrating two systems and I've been banging my head against this for hours... I'm stuck on something that should probably be simple. I'm working with a crash in my iOS 17 app when trying to fetch records from Core Data using Swift Concurrency. The app compiles and runs fine until I attempt to call my async function that retrieves data. The crash log shows an 'unrecognized selector sent to instance' behavior, which points to an scenario in how I'm accessing the managed object context. My model is set up as follows: ```swift class MyEntity: NSManagedObject { @NSManaged var name: String? @NSManaged var age: Int16 } ``` And I'm trying to fetch it like this: ```swift func fetchEntities() async throws -> [MyEntity] { let context = PersistenceController.shared.container.viewContext let request: NSFetchRequest<MyEntity> = MyEntity.fetchRequest() return try await context.perform { () -> [MyEntity] in return try context.fetch(request) } } ``` However, when I call `await fetchEntities()` from my view model, the app crashes with the following behavior message: ``` Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[MyEntity name]: unrecognized selector sent to instance' ``` I've confirmed that `MyEntity` is properly registered with the Core Data stack and I verified the model is up to date. I've also tried moving the async call to a different part of the lifecycle and re-testing, which did not resolve the scenario. Could this be related to the way I’m using `perform` with the context? Any insights or suggestions on how to resolve this would be greatly appreciated. I'm working on a application that needs to handle this. What am I doing wrong? This is part of a larger service I'm building. Any ideas how to fix this?