CoreData CRUD methods in Swift 2.0

CoreData CRUD methods in Swift 2.0

With Swift 2.0, Apple introduced a protocol oriented way of programming. I want to use this to create a protocol that adds CRUD functionality to CoreData models without the need for all the type casting.

import Foundation  
import CoreData

protocol CoreDataCRUD {

}

extension CoreDataCRUD where Self : NSManagedObject {  
    static func create() -> Self {
        return NSEntityDescription.insertNewObjectForEntityForName(Utility.classNameAsString(self), inManagedObjectContext: sharedCoreDataManager.context()) as! Self
    }

    static func findById(id: String) throws -> Self? {
        let fetchRequest = NSFetchRequest(entityName: Utility.classNameAsString(self))
        let predicate = NSPredicate(format: "id == %@", id)
        fetchRequest.predicate = predicate
        if let fetchResults = try sharedCoreDataManager.context().executeFetchRequest(fetchRequest) as? [Self] {
            if fetchResults.count > 0 {
                return fetchResults[0]
            }
        }
        return nil    
    }

    func delete() throws {
        (self as! NSManagedObject).removeEntity()
    }
}
class Utility{  
    class func classNameAsString(obj: Any) -> String {
        return _stdlib_getDemangledTypeName(obj).componentsSeparatedByString(".")[1]
    }
}

We add the protocol CoreDataCRUD to every model we want like this.

class FooModel: NSManagedObject, CoreDataCRUD {  
}

Now we can use the protocol methods like this:

var foo = FooModel.create()  
var foo = try FooModel.findById(<id>) ?? FooModel.create()  
Thomas Sattlecker

Thomas Sattlecker

View Comments
Navigation