Search code examples
objective-cswiftswiftuinsmanagedobjectswift5

Unable to cast element in ForEach Loop to NSManagedObject Subclass SwiftUI


I got a ListView in SwiftUI and want to generate RowViews depending on a given property. Therefore I want to check the property of the element in the ForEach loop.

Xcode does not recognize the type of the element, thats why i want to cast the element to the correct Class which is an NSManagedObject Subclass.

I created the NSManagedObject Subclass from the xcdatamodeld (Editor -> Create NSManagedObject Subclass...).

The NSManagedObject Subclass is created in objective-c and I added the .h file to the bridging header.

I have no problem working with the NSManagedObject Subclass in the rest of the project. I can even create an property of that Type in the same Struct like so:

struct MyListView: View {

    var test : MyNSManagedObjectSubclass //Xcode does recognize it here

For some reason Xcode wont recognize the NSManagedObject Subclass inside the ForEach Loop.

code looks like:

struct MyListView: View {

    var test : MyNSManagedObjectSubclass //Xcode does recognize it here
    @EnvironmentObject private var fetchResultsContainer : FetchedResultsContainer

    var body: some View {
        NavigationView{
            VStack{
                ForEach(fetchResultsContainer.results , id: \.identifier) { result in
                    if let castedResult = result as! MyNSManagedObjectSubclass { //Xcode does not recognize it here
                        if castedResult.property{
                            ResultRowView(input: result)
                        }
                    }
                }
            }
        }
    }
}

FetchedResultsContainer:

@objc class FetchedResultsContainer : NSObject, ObservableObject{

    @objc @Published var results: [MyNSManagedObjectSubclass]()

    @objc static let sharedInstance: FetchedResultsContainer = {
        let instance = FetchedResultsContainer()

        return instance
    }()
}

I feel like im missing something obvious, as im still quite new to Swift and SwiftUI. Appreciate your help.


Solution

  • Ok after taking a step back and simply coding it again from scratch it simply worked an no casting was needed...

    List(fetchResultsContainer.results, id: \.identifier) { result in
        if (result.property == 0) {
        //do something
        }
    }
    

    My assumption that the casting was not working was not correct. I probably checked result.property == false, with property being of type NSNumber and it gave out some strange compile errors that led me on the wrong path.