I would like to create a function that would handle any type of object which have overriden init functions. As far I've got working with only overriden init function but if i want to do smth else with these objects every time i have to write extra code with some logic parts. To avoid that and makes code clean i have to make generic functions witch going to have as an argument T.Type
.
This is my sample code which shows working parts :
import Foundation
import CoreData
extension Sample {
@nonobjc public class func fetchRequest() -> NSFetchRequest<Sample> {
return NSFetchRequest<Sample>(entityName: "Sample");
}
@NSManaged public var smth: String
@NSManaged public var smth1: Double
convenience init(smth: String, smth1: Double, insertIntoManagedObjectContext _context: NSManagedObjectContext!) {
let _enitity = NSEntityDescription.entity(forEntityName: "Sample", in: _context)
self.init(entity: _entity, insertInto: _context)
self.smth = smth
self.smth1 = smth1
}
}
And then I initialize the object like this :
let _context = DataBaseController.getContext()
let _sample: Sample = Sample(smth: smth, smth1: smth1 insertIntoManagedObjectContext: _context)
DataBaseController.saveContext()
By following exapmle from here : Example
I've implemented these functions :
func addRecord<T: NSManagedObject>(_ type : T.Type) -> T {
let _entityName = T.description()
let _context = DataBaseController.persistentContainer.viewContext
let _entity = NSEntityDescription.entity(forEntityName: _entityName, in: _context)
let _record = T(entity: _entity!, insertInto: _context)
return _record
}
func recordsInDataBase<T: NSManagedObject>(_ type : T.Type) -> Int {
let _records = allRecords(T.self)
return _records.count
}
func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T] {
let _context = DataBaseController.persistentContainer.viewContext
let _request = T.fetchRequest()
do {
let _results = try _context.fetch(_request)
return _results as! [T]
} catch {
print("Error : \(error)")
return []
}
}
My question is : How could I invoke my overriden init function from the class with passing also these 2 extra arguments which is smth
and smth1
?
let _sample = DataBaseController.Instance.addRecord(...)
Thanks in advance!
EDIT :
Is it going to be like this ? :
let _sample = DataBaseController.Instance.addRecord(Sample.self.init(smth: smth, smth1: smth1, insertIntoManagedObjectContext: _context))