jessesquires / JSQCoreDataKit

A swifter Core Data stack
https://jessesquires.github.io/JSQCoreDataKit/
MIT License
616 stars 70 forks source link

Better API for creating entity descriptions and inserting managed objects #87

Closed jessesquires closed 8 years ago

jessesquires commented 8 years ago

Would like to improve the existing entity() func, and provide a better/easier way to create an entity description and insert managed objects.

Daniel has great approaches outlined in this talk: https://realm.io/news/tryswift-daniel-eggert-modern-core-data/

I think we should do this, or something similar.

jessesquires commented 8 years ago

Generate entity name via "\(self.dynamicType.self)" ?

jessesquires commented 8 years ago

Could implement this in v4.x and keep existing entity() marked as deprecated, then we can remove this v5.0

jessesquires commented 8 years ago

Draft design:

protocol CoreDataEntityProtocol {
    static var entityName: String { get }

    static var defaultSortDescriptors: [SortDescriptor] { get }
}

extension CoreDataEntityProtocol where Self: NSManagedObject {

    static func defaultEntityName() -> String {
        return "\(Self.self)"
    }

    static var fetchRequest: NSFetchRequest<Self> {
        let request = NSFetchRequest<NSManagedObject>(entityName: entityName)
        request.sortDescriptors = defaultSortDescriptors
        return request as! NSFetchRequest<Self>
    }

    static func entity(context: NSManagedObjectContext) -> NSEntityDescription {
        return NSEntityDescription.entity(forEntityName: entityName, in: context)!
    }
}