Convert request Function to Generic type

前端 未结 1 544
悲&欢浪女
悲&欢浪女 2020-12-21 21:17

I am trying to convert my below fetch request code from core data to generic type.

let request = NSPredicate(format: \"name == %@ AND password == %@ AND type         


        
相关标签:
1条回答
  • 2020-12-21 22:14

    According to my comment I recommend to use a protocol with extension for example

    protocol Fetchable
    {
        associatedtype FetchableType: NSManagedObject = Self
    
        static var entityName : String { get }
        static var managedObjectContext : NSManagedObjectContext { get }
        static func objects(for predicate: NSPredicate?) throws -> [FetchableType]
    }
    
    extension Fetchable where Self : NSManagedObject, FetchableType == Self
    {
        static var entityName : String {
            return NSStringFromClass(self).components(separatedBy: ".").last!
        }
    
        static var managedObjectContext : NSManagedObjectContext {
            return (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        }
    
        static func objects(for predicate: NSPredicate?) throws -> [FetchableType]
        {
            let request = NSFetchRequest<FetchableType>(entityName: entityName)
            request.predicate = predicate
            return try managedObjectContext.fetch(request)
        }
    }
    

    Change (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext to the reference to your managed object context.

    Make all NSManagedObject subclasses adopt Fetchable. There is no extra code needed in the subclasses.

    Now you can get the data with

    do {
       let predicate = NSPredicate(format: ...
       let objects = try MyEntity.objects(for: predicate)
    } catch {
        print(error)
    }
    

    That's all, objects are [MyEntity] without any type casting and always non-optional on success.

    The protocol is easily extendable by default sorting descriptors, sorting directions etc.

    0 讨论(0)
提交回复
热议问题