我正在使用SwiftUI开发我的应用程序,对于我的数据库,我选择使用领域数据库。
我的应用程序记录驱动程序Trip状态和统计数据看起来类似于这个对象:
class TripModel: Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var id: ObjectId
@Persisted var tripMaxSpeed: String = "0"
@Persisted var tripAvgSpeed: String = "0"
@Persisted var tripDistance: String = "0"
@Persisted var tripDuration: Int = 0
@Persisted var tripDate: Date = Date()
@Persisted var tripFavorite: Bool = false
var coordinates = List<TripRoute>() // We have a list of CLCoord2D we want to cast it to TripRoute
}
class TripRoute: Object {
@Persisted var latitude = 0.0
@Persisted var longitude = 0.0
/// Computed properties are ignored in Realm
var coordinate: CLLocationCoordinate2D {
return CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
}当用户打开应用程序时,他们有一个按钮来启动行程,并且trip状态在我的viewModel中开始更新,我也有一个布尔变量,当我的用户按下该按钮以启动trip时,就像下面的代码一样。
class LocationManager: NSObject, ObservableObject {
@Published var startTrip = false {
didSet {
//When trip start == true then rest all value and start from zero
if startTrip == true {
tripTimer = 0
allSpeeds.removeAll()
tripMaxSpeed = 0
tripDistance = 0
allLocations.removeAll()
}
//When Trip ends write the trip to Realm Database for Saving
if startTrip == false {
addTrip()
}
}
}
}正如上面的代码所解释的,每当开始行程值更改为false时,就会使用addTrip()函数将新trip添加到数据库中,并且除了未能添加的数组坐标之外,所有操作都很好,下面是addTrip()函数:
func addTrip() {
if let localRealm = localRealm {
do {
print("DEBUG: Trying to add trip")
try localRealm.write({
let trip = TripModel()
for location in allLocations {
let tripRoute = TripRoute()
tripRoute.latitude = location.longitude
tripRoute.longitude = location.longitude
trip.coordinates.append(tripRoute)
}
trip.tripMaxSpeed = tripMaxSpeed.converted.roundedString
trip.tripAvgSpeed = allSpeeds.average()
trip.tripDistance = tripDistance.convertDistance.roundedString1
trip.tripDuration = tripTimer
trip.tripDate = Date()
localRealm.add(trip)
getTrips()
})
} catch {
print("ERROR: error adding trip to realm \(error.localizedDescription)")
}
}
}除了tripInformation之外,所有的tripRoute都被成功地添加了,并且所有的tripRoute都没有问题,我不知道为什么对象中的数组是空的,并且不保存。
我想要完成的坐标列表,是显示用户跟踪线在他们的历史地图,他们采取的旅行。
发布于 2022-09-26 16:36:51
您也需要持久化容器。
@Persisted var coordinates = List<TripRoute>()TripRoute对象可能存储在数据库中的某个地方,但是没有任何东西将它们绑定到TripModel对象。
https://stackoverflow.com/questions/73854475
复制相似问题