1

I'm trying to create a generic single repository class that can both save and fetch whatever entity you ask it to, likely inferred by object type. I'm using this question as a base.

I was trying to bypass having to pass an NSManagedObjectContext in to an entity, and have the Repository do this instead. Is this possible?

The ideal method signature to save an entity would be the following, where entity is a subclass of NSManagedObject with a few properties:

Repository(persistentContainer).save(entity)

NSManagedObject Extension

extension NSManagedObject
{
    class func createInContext<T>(context:NSManagedObjectContext, type : T.Type) -> T {
        return unsafeDowncast(NSEntityDescription.insertNewObject(forEntityName: entityName(), into: context), to: self) as! T
    }

    class func entityName() -> String {
        let classString = NSStringFromClass(self)

        return classString.components(separatedBy: ".").last ?? classString
    }
}

Repository Save Method

public func save<T>(entity: T) -> Void where T: NSManagedObject
{
    self.container.performBackgroundTask { (context) in    
        let object = T.self.createInContext(context: context, type: T.self)
        // Error checking removed for brevity    
        try! context.save()
    }
}

The error that I get at runtime is:

Failed to call designated initializer on NSManagedObject class 'UUID'

and below it...

[AppName.Uuid setUuid:]: unrecognized selector sent to instance

Which one is it then? Is it possible to bypass having to pass the context in every time with this method or not? Is there an alternative solution to achieve what I am after?

Jimbo
  • 25,790
  • 15
  • 86
  • 131
  • Why do you need unsafeDowncast ? How does your Uuid class look like, it should be marked as NSManaged and properties need to be dynamic – Sandeep Feb 27 '18 at 20:51
  • @Sandeep There are two `NSManaged` properties, just scalars, and unsafeDowncast was required instead of `unsafeBitCast`, from [this answer](https://stackoverflow.com/a/27112385/736809). I added dynamic and it made no difference – Jimbo Feb 27 '18 at 20:53

0 Answers0