I'm working on a SwiftUI app that makes use of Core Data. I have a list of exercises as entities and I have a List in which every exercise can be marked as favorite using a swipe action:
struct ExerciseListView: View {
@Environment(\.managedObjectContext) private var viewContext
private var fetchRequest: FetchRequest<Exercise>
private var exerciseList: FetchedResults<Exercise> { return fetchRequest.wrappedValue }
private let exercises: ExerciseList
@State private var searchText = ""
init(list: ExerciseList) {
self.exercises = list
self.fetchRequest = Exercise.fetchExerciseInExerciseList(withListName: list.name)
}
var body: some View {
List(exerciseList, id: \.self) { exercise in
NavigationLink {
ExerciseView()
.environmentObject(exercise)
} label: {
if (exercise.favorite) {
Label(exercise.name, image: "star.fill")
.accentColor(.yellow)
} else {
Text(exercise.name)
}
}.swipeActions {
Button {
toggleFavorite(exercise)
} label: {
Label(NSLocalizedString("Favorite", comment: ""), image: "star")
}
}
}
.searchable(text: $searchText, prompt: NSLocalizedString("Search", comment: ""))
.onChange(of: searchText, perform: { newValue in
guard !newValue.isEmpty else {
exerciseList.nsPredicate = nil
return
}
exerciseList.nsPredicate = NSPredicate(format: "%K CONTAINS[cd] %@", argumentArray: [#keyPath(Exercise.name), newValue])
})
.navigationBarTitle(exercises.name)
.navigationBarTitleDisplayMode(NavigationBarItem.TitleDisplayMode.automatic)
}
private func toggleFavorite(_ exercise: Exercise) {
Exercise.toggleFavorite(exercise, in: viewContext)
}
}
The toggleFavorite
method looks like this:
static func toggleFavorite(_ exercise: Exercise, in context: NSManagedObjectContext) {
exercise.favorite.toggle()
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
The problem I'm having is that if I execute the app in an emulator or my physical phone by hitting the run button, I can easily mark and unmark an exercise as a favourite, but if I make a release of my app and upload it to TestFlight, it just doesn't work. Is there any way I can debug the problem or maybe log what's happening?
Why could this be happening?
Thanks a lot in advance!