Skip to content

Instantly share code, notes, and snippets.

@rnapier
Last active April 23, 2016 23:21
Show Gist options
  • Select an option

  • Save rnapier/edb1a5dda76eb37c39dc to your computer and use it in GitHub Desktop.

Select an option

Save rnapier/edb1a5dda76eb37c39dc to your computer and use it in GitHub Desktop.
// This should all be on the MOC, not the class.
// A singleton MOC like "CoreDataStack" completely blows up CoreData concurrency.
// You need a separate MOC per queue. So you have to work with the right MOC, not a global one.
// (I'm assuming here that CoreDataStack returns a singleton; maybe it makes a new one magically;
// either way, you should work through the moc so that you have a consistent view of the store.)
// Built on the MOC, this is easy, and matches stuff we've done in ObjC for years.
extension NSManagedObjectContext {
func newInstanceOf<T: NSManagedObject>(type: T.Type) -> T {
return NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(T), inManagedObjectContext: self) as! T
}
func allInstancesOf<T: NSManagedObject>(type: T.Type) -> [T] {
let fetchRequest = NSFetchRequest(entityName: NSStringFromClass(T))
fetchRequest.entity = NSEntityDescription.entityForName(NSStringFromClass(T), inManagedObjectContext: self)
return try! self.executeFetchRequest(fetchRequest) as! [T]
}
func findInstance<T: NSManagedObject>(predicate: T -> Bool) -> T? {
return allInstancesOf(T).lazy.filter(predicate).first
}
}
let moc = CoreDataStack.managedObjectContext
let obj = moc.newInstanceOf(MyObject) // type == MyObject
let all = moc.allInstancesOf(MyObject) // type == [MyObject]
let f = moc.findInstance{ (obj: MyObject) in obj.name == "" } // type == MyObject?
let g: MyObject? = moc.findInstance{ $0.name == "" } // Or be explicit so we can use $0
@JessyCatterwaul
Copy link
Copy Markdown

Thanks! I'm sure I'll be using something very similar to this when I need to worry about concurrency. I'm working on my first non-Unity-based iOS project now, and learning a bunch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment