0
\$\begingroup\$

I am not very familiar with CoreData, some I am not sure if the way I am handling relationships between objects is the right way to do it.

I have the following entities:

Entity: CD_User_Minimal
Property: identifier -> Int64

Entity: CD_Comment
Property: text -> String
Relationship: user -> CD_User_Minimal

When a new comment will come through the app, I am currently checking there is already a user saved with the identifier. This is what kind of data I retrieve:

{"text": "This is some comment", "posted_by_identifier": 1234567890}

This is my code for mapping:

// I am on a development toolchain so not sure if this constraint works for the current stabile toolchain
protocol CoreDataProtobufMappable: NSManagedObject {
    static func createIdentifierPredicate(identifier: Int64) -> NSPredicate
    func mapFrom(message: Data)
}

extension CoreDataProtobufMappableUnique {
    static func mapFrom(message: Data) -> Self {
        let fetchRequest: NSFetchRequest<Self> = Self.fetchRequest() as! NSFetchRequest<Self>

        fetchRequest.predicate = Self.createIdentifierPredicate(identifier: message.identifier) // This won't work, but you get the idea.
        // CoreDataContext is the singleton of the default container.
        let result = try! CoreDataContext.persistentContainer.viewContext.fetch(fetchRequest)
        // No more than 1 result should be found
        assert(result.count <= 1)

        guard let first = result.first else {
            let _self = Self.init(context: CoreDataContext.persistentContainer.viewContext)

            _self.mapFrom(message: data)

            return _self
        }

        first.mapFrom(message: data)

        return first
    }
}

I am wondering if this is the right way to do it. I am creating a new object if there isn't one in the database. If at least one result is found, I am reusing that object.

That object can be in multiple NSFetchResultControllers, which therefore will trigger an update event. Besides that, the CD_User_Minimal will have lots of other relationships by other entities.

Is this is the right way for handling objects in CoreData? Can I expect performance issues when lots of objects are inserted? Can race conditions easily occur? Are there chances of retain cycles?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.