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?