Skip to content

Instantly share code, notes, and snippets.

@jkubicek
Created July 2, 2015 04:45
Show Gist options
  • Save jkubicek/48b947eed5ac0c32cf92 to your computer and use it in GitHub Desktop.
Save jkubicek/48b947eed5ac0c32cf92 to your computer and use it in GitHub Desktop.
managed object creation extension
protocol ManagedObject {
static var entityName: String { get }
}
extension ManagedObject where Self: NSManagedObject {
static func createWithContext(context: NSManagedObjectContext) -> Self {
return Self.createWithContext(context, entityName: self.entityName)
}
}
extension NSManagedObject {
private
class func createWithContext<T: NSManagedObject>(context: NSManagedObjectContext, entityName: String) -> T {
let obj = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: context)
return obj as! T
}
}
@rgcottrell
Copy link

I got this to work with the master detail template:

protocol CoreDataExtensions {}

extension CoreDataExtensions {
    static func newObjectInContext(moc: NSManagedObjectContext, entityName: String) -> Self {
        return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: moc) as! Self
    }
}

extension NSManagedObject: CoreDataExtensions {}

@jkubicek
Copy link
Author

jkubicek commented Jul 2, 2015

I thought we had tried the as! Self cast and the compiler complained? I wonder if your solution is different from what I was trying earlier in some way I'm not seeing. I'll try again tomorrow.

@rgcottrell
Copy link

The Self cast works because it's in a protocol extension and not a class extension!

@rgcottrell
Copy link

A variation of your code with a sample subclass. It's not completely awful, I guess:

protocol ManagedObject {
    static var entityName: String { get }
}

extension ManagedObject  {
    static func createWithContext(moc: NSManagedObjectContext) -> Self {
        return NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: moc) as! Self
    }
}

// Add conformance to managed object subclass.
extension Event: ManagedObject {
    static var entityName: String {
        return "Event"
    }
}

@jkubicek
Copy link
Author

jkubicek commented Jul 2, 2015

Yeah, that's better, though I plan on adding more NSManagedObject-specific methods to the extension eventually.

You can simplify the entityName param in the Event object:

extension Event: ManagedObject {
    static var entityName = "Event"
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment