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
}
}
@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