HomeiOS Developmentios - use relationships in CoreData to have the ability to...

ios – use relationships in CoreData to have the ability to entry the info?


I’ve encountered an issue with including information to CoreData. the logic is that when the person faucets on “save” button, this system provides the info (time period, definition, tag, date) to FlashCardData, and in addition, identify and date for the set of flashcards. I’ve two entities since I want to use relationships between them so as to entry the info from one and to make use of in one other. In my case, use information from FlashCardData in FlashSets so as to create a set of flashcards.

Nonetheless, my method appears to not work as I am receiving errors relating to the utilization of optionals like this: ‘Initializer for conditional binding will need to have Optionally available sort, not ‘FlashSets”. At this level of studying use CoreData I am caught, is there a solution to remedy this?
This is the code the place i am including information to CoreData (TermDefinitionView):

.navigationBarItems(trailing: Button(motion: {
                        // Create new FlashSets
                        
                       // currentSet = dataController.addName(identify: identify, date: Date(), playing cards: [], context: managedObjectContext)
                        let newSetOptional = dataController.addName(identify: identify, date: Date(), playing cards: [], context: managedObjectContext)
                        
                        if let newSet = newSetOptional {
                                dataController.savedFlash = []

                                // Create new FlashCardData for every time period/definition/tag in viewModel.termdefpairs and affiliate with newSet
                                for testForm in viewModel.termdefpairs {
                                    let card = dataController.add(time period: testForm.time period, definition: testForm.definition, tag: testForm.tag, date: Date(), set: newSet, context: managedObjectContext)
                                    dataController.savedFlash.append(card)
                                    newSet.addToCards(card)
                                }
                                dataController.save(context: managedObjectContext)
                                
                                currentSet = newSet // Assuming currentSet is a state variable to carry the present set
                                isShowingSet = true
                                dismiss()
                            }
                    }) {
                        Textual content("Save")
                        if let currentSet = currentSet {
                            NavigationLink(vacation spot: SetView(flashSet: currentSet, flashCardData: _flashCardData), isActive: $isShowingSet) {
                                EmptyView()
                            }
                        }
                    })

DataController to deal with information:

class DataController: ObservableObject {
    static let shared = DataController()
    @Printed var savedFlash: [FlashCardData] = []
    let container: NSPersistentContainer
    let fetchRequest: NSFetchRequest<FlashCardData> = FlashCardData.fetchRequest()
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(identify: "CoreData")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Exchange this implementation with code to deal with the error appropriately.
                // fatalError() causes the applying to generate a crash log and terminate. You shouldn't use this perform in a delivery utility, though it could be helpful throughout improvement.

                /*
                 Typical causes for an error right here embody:
                 * The dad or mum listing doesn't exist, can't be created, or disallows writing.
                 * The persistent retailer shouldn't be accessible, on account of permissions or information safety when the machine is locked.
                 * The machine is out of area.
                 * The shop couldn't be migrated to the present mannequin model.
                 Verify the error message to find out what the precise drawback was.
                 */
                fatalError("Unresolved error (error), (error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
    
    func save(context: NSManagedObjectContext) {
        do {
            attempt context.save()
            print("Knowledge saved")
        } catch {
            print("We couldn't save the info...")
        }
    }
    func add(time period: String, definition: String, tag: String, date: Date, set: FlashSets, context: NSManagedObjectContext) -> FlashCardData  {
        let information = FlashCardData(context: context)
    //    flashCardData.flashSet = flashSet
        information.id = UUID()
        information.definition = definition
        information.time period = time period
        information.tag = tag
        information.date = date
        information.set = set
        save(context: context)
        return information
    }
    func addName(identify: String, date: Date, playing cards: [FlashCardData], context: NSManagedObjectContext)  -> FlashSets {
        let information = FlashSets(context: context)
        information.identify = identify
        information.date = date
        information.addToCards(NSSet(array: playing cards))
        save(context: context)
        return information
    }

After the button was tapped and the info added, I am fetching it right here(SetView):

struct SetView: View {
    
    var flashSet: FlashSets
    @Surroundings(.managedObjectContext) non-public var viewContext
   // @FetchRequest(entity: FlashCardData.entity(), sortDescriptors: NSSortDescriptor[key: ])
    @FetchRequest(
        entity: FlashCardData.entity(),
        sortDescriptors: [NSSortDescriptor(keyPath: FlashCardData.date, ascending: false)],
        predicate: NSPredicate(format: "date > %@", Date().addingTimeInterval(1) as NSDate)
    ) var flashCardData: FetchedResults<FlashCardData>
    
    let dataController = DataController.shared
    var elimination: (() -> Void)? = nil
    var onRemove: ((SwipeDirection) -> Void)? = nil
    @State non-public var isShown = false
    @State non-public var offset = CGSize.zero
    @State non-public var label: String = "Nonetheless Studying"  // Outline a label string
    @State non-public var showPositiveIndicator = false
    @State non-public var showNegativeIndicator = false
    @State non-public var showMiddleIndicator = false
    @State non-public var showEasyIndicator = false
    @State var redirectToSet = false
    var physique: some View {
       
            
        if let playing cards = flashSet.playing cards?.allObjects as? [FlashCardData] {
            ForEach(playing cards) { card in
                Textual content(card.time period ?? "")
            }
            // Now flashcards is an array of FlashCardData
        }
            //remainder of the code...
        NavigationStack {
            ZStack {
                    ForEach(flashCardData, id: .self) { flashcards in
                        //   FlashcardView(flashcard: flashcard)
                        
                        SingleFlashCard(card: flashcards)
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments