swiftcore-datansmanagedobjectclean-architecturensmanagedobjectmodel

How to map model for NSManagedObject?


When I try to do this, the model is stored in the NSManagedObjectContext if I use the context, and without it it throws an error, but I'm not expecting the same result. Is there an easy way to implement this?

class WordDal: NSManagedObject {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<WordDal> {
        return NSFetchRequest<WordDal>(entityName: "WordDal")
    }

    @NSManaged public var word: String?
    @NSManaged public var uuid: UUID?
}

struct WordPresentation {
    let word: String
    let uuid: UUID
}

func mappingNSManagedObject(_ wordPresentation: WordPresentation) -> WordDal {
    let model = WordDal()
    model.uuid = wordPresentation.uuid
    model.word = wordPresentation.word
    return model
}

enter image description here


Solution

  • I solved the problem like this (I don't know why I put it off and didn't understand right away):

    class WordDal: NSManagedObject {
        @nonobjc public class func fetchRequest() -> NSFetchRequest<WordDal> {
            return NSFetchRequest<WordDal>(entityName: "WordDal")
        }
    
        @NSManaged public var word: String?
        @NSManaged public var uuid: UUID?
    }
    
    struct WordPresentation {
        let word: String
        let uuid: UUID
    }
    
    func removeFromStorage(by uuid: UUID) {
        getDataFromStorage { [weak self] objects  in
            guard let self = self else { return }
            if let objectForRemove = objects.first(where: { $0.uuid == uuid }) {
            self.coreDataStack.mainContext.delete(objectForRemove)
            self.coreDataStack.saveContext(self.managedObjectContext)
            }
        }
    }
    
    

    I'm creating a presentation level model with UUID! And I delete only on him himself UUID. Now I can walk both ways.