Created
September 16, 2015 03:17
-
-
Save JessyCatterwaul/f2069bac578d74af3206 to your computer and use it in GitHub Desktop.
Strongly-typed Core Data ideas
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
import CoreData | |
/// Designed to add functionality to classes deriving from *NSManagedObject* | |
protocol Managed {} | |
// This keeps us from having to explicitly implement Managed | |
// on all NSManagedObject subclasses. | |
extension NSManagedObject: Managed {} | |
// Managed is extended instead of NSManagedObject, | |
// so that we can work with derived types, and avoid casting externally. | |
extension Managed where Self: NSManagedObject { | |
static var newManagedObject: Self { | |
return NSEntityDescription.insertNewObjectForEntityForName(className, | |
inManagedObjectContext: CoreDataStack.managedObjectContext | |
) as! Self | |
} | |
static var storedInContext: [Self] { | |
let fetchRequest = NSFetchRequest(entityName: className) | |
fetchRequest.entity = NSEntityDescription.entityForName(className, | |
inManagedObjectContext: CoreDataStack.managedObjectContext | |
)! | |
return try! CoreDataStack.managedObjectContext.executeFetchRequest(fetchRequest) | |
as! [Self] | |
} | |
} | |
// Keep this in another file. | |
public extension NSObject { | |
public static var className: String { | |
return NSStringFromClass(self).componentsSeparatedByString(".").last! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment