Setup:
My app uses a SwiftUI Map
with annotations. The annotations should be instances of a Place
class defined as:
final class Place: NSManagedObject, UpdateTimestampable, Identifiable {
@NSManaged var horizontalAccuracy: Double
@NSManaged var latitude: Double
@NSManaged var longitude: Double
@NSManaged var name: String
@NSManaged var namesOfItemsBoughtHere: Set<String>?
@NSManaged var radius: Double
@NSManaged var updatedAt: Date?
var coordinate: CLLocationCoordinate2D {
var coord = CLLocationCoordinate2D()
if let context = self.managedObjectContext {
context.performAndWait {
coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
} else {
fatalError("Place without context")
}
return coord
}
}
The places used as annotations in a specific map are defined by a MapViewModel:
let placesForBuyLocationNames = mapViewModel.placesForBuyLocationNames()
Problem:
When these places are used directly as annotations, a run time error is generated:
let annotations = placesForBuyLocationNames
Map(coordinateRegion: $region,
interactionModes: .all,
showsUserLocation: false,
annotationItems: annotations) { annotation in
MapAnnotation(coordinate: annotation.coordinate, anchorPoint: CGPoint(x: 0.5, y: 1)) {
AnnotationView(region: region, buyPlaceNameBeforeDragging: annotation.name, mapviewModel: mapViewModel)
}
}
Run time error:
Publishing changes from within view updates is not allowed, this will cause undefined behavior.
No run time error is however generated, if these places are mapped to a helper struct and these structs are used as annotations:
struct Annotation: Identifiable {
let id = UUID()
let name: String
let coordinate: CLLocationCoordinate2D
}
// …
let annotations = placesForBuyLocationNames.map { Annotation(name: $0.name, coordinate: $0.coordinate) }
Questions:
What could be the reason for this run time error?
Is anything wrong with my code?