How to map model for NSManagedObject?

308 Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

2
On

Consider to redesign your model to have computed property for the new wrapper type that transforms the property value to and from the wrapper value.

Implementing a computed property in a Swift Core Data model is often a clear, more intuitive way to achieve what you need.

Here is an example implementation:

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

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?
    
    var wordPresentation : WordPresentation {
        get {
            return WordPresentation(word: self.word, uuid: self.uuid)
        }
        set {
            self.word = newValue.name
            self.uuid = newValue.id
        }
    } 
}