Skip to content

Instantly share code, notes, and snippets.

@keybuk
Last active August 29, 2015 14:26
Show Gist options
  • Save keybuk/317944cbee504e78d7d1 to your computer and use it in GitHub Desktop.
Save keybuk/317944cbee504e78d7d1 to your computer and use it in GitHub Desktop.
public enum Model: String {
case Company
case Team
case Employee
}
extension NSEntityDescription {
public class func entity(model: Model, inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription {
// Since we know we always have a matching entity, we can just force-unwrap this.
return NSEntityDescription.entityForName(model.rawValue, inManagedObjectContext: context)!
}
}
extension NSFetchResult {
public convenience init(model: Model) {
self.init(name: model.rawValue)
}
}
public final class Employee: NSManagedObject {
// properties here
public init(/* properties here */, inManagedObjectContext context: NSManagedObjectContext) {
let entity = NSEntityDescription.entity(Model.Employee, inManagedObjectContext: context)
super.init(entity: entity, insertIntoManagedObjectContext: context)
// initialize properties
}
}
// To create an object:
Employee(..., inManagedObjectContext: context)
// To create a fetch result:
NSFetchResult(model: Model.Employee)
public enum Model: String {
case Company
case Team
case Employee
public func entityInManagedObjectContext(context: NSManagedObjectContext) -> NSEntityDescription {
// Since we know we always have a matching entity, we can just force-unwrap this.
return NSEntityDescription.entityForName(self.rawValue, inManagedObjectContext: context)!
}
public func fetchResult() -> NSFetchResult {
return NSFetchResult(name: self.rawValue)
}
}
public final class Employee: NSManagedObject {
// properties here
public init(/* properties here */, inManagedObjectContext context: NSManagedObjectContext) {
let entity = Model.Employee.entityInManagedObjectContext(context)
super.init(entity: entity, insertIntoManagedObjectContext: context)
// initialize properties
}
}
// To create an object:
Employee(..., inManagedObjectContext: context)
// To create a fetch result:
Model.Employee.fetchResult()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment