Last active
August 29, 2015 14:26
-
-
Save keybuk/317944cbee504e78d7d1 to your computer and use it in GitHub Desktop.
This file contains 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
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) |
This file contains 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
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