Created
July 2, 2015 04:45
-
-
Save jkubicek/48b947eed5ac0c32cf92 to your computer and use it in GitHub Desktop.
managed object creation extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
A variation of your code with a sample subclass. It's not completely awful, I guess: