When I run my app, SwiftUI occasionally flags a runtime error stating that "Modifying state during view update, this will cause undefined behavior." When looking into this error it points directly to the @main
attribute on my struct that conforms to the App protocol. On closer inspection, it points to Core Data calling the coder initialiser for my StoredRoutes
type (a type that conforms to NSSecureCoding
and has a single instance property containing an array of Route
(custom enumeration representing train routes)). I'm confused on how to proceed to fix the error.
SwiftUI modifying state warning - pointing to @main
May be you could show some code ? Or at least the detailed log report.
Here's my custom StoredRoutes type:
import Foundation
final class StoredRoutes: NSObject, NSSecureCoding {
static var supportsSecureCoding: Bool = true
func encode(with coder: NSCoder) {
var routeids: [NSString] = []
for route in routes {
routeids.append(NSString(string: route.rawValue))
}
coder.encode(NSArray(array: routeids), forKey: "routes")
}
init?(coder: NSCoder) {
if let nsArray = coder.decodeObject(of: NSArray.self, forKey: "routes") {
self.routes = []
for id in nsArray {
self.routes.append(Route(rawValue: id as! String)!)
}
} else {
return nil
}
}
var routes: [Route]
required init(routes: [Route]) {
self.routes = routes
}
}
and my value transformer:
import Foundation
final class StoredRoutesValueTransformer: NSSecureUnarchiveFromDataTransformer {
static var name = NSValueTransformerName(rawValue: "StoredRoutesValueTransformer")
override class func allowsReverseTransformation() -> Bool {
return true
}
override class func transformedValueClass() -> AnyClass {
return StoredRoutes.self
}
override class var allowedTopLevelClasses: [AnyClass] {
return [StoredRoutes.self, NSArray.self, NSString.self]
}
override func transformedValue(_ value: Any?) -> Any? {
guard let data = value as? Data else {
fatalError("Wrong data type: value must be of type Data. The type the value recieved was \(type(of: value)).")
}
return super.transformedValue(data)
}
override func reverseTransformedValue(_ value: Any?) -> Any? {
guard let storedRoutes = value as? StoredRoutes else {
fatalError("Wrong data type: value must be of type StoredRoutes. The type of the value recieved was \(type(of: value))")
}
return super.reverseTransformedValue(storedRoutes)
}
public static func register() {
let transformer = StoredRoutesValueTransformer()
ValueTransformer.setValueTransformer(transformer, forName: name)
}
}
I am also experiencing this. I didn't make any changes that effect any kind of state whatsoever. I merely attempted to edit the Entitlements File, and then undid the changes. This error appeared and now it won't go away. Even reverting to previous builds doesn't make it stop