Skip to content
kevindelord edited this page Jun 28, 2016 · 8 revisions

Fetch entities with MagicalRecord

To read or fetch entities in the default context you need to use NSPredicate and Magical Record.

The official documentation shows how to use predicates, sorting attributes, etc.

Here is an example showing how to fetch an array of entities depending on their attributes:

class func entityForDestination(destination: String) -> [Plane] {
	let predicate = NSPredicate(format: "destination == %@" destination)
	let entities = Plane.MR_findAllSortedBy(Plane.sortingAttributeName(), ascending: true, withPredicate: predicate)
	return (entities as? [Plane] ?? [])
}

Note that the call to Plane.sortingAttributeName() returns the default sorting attribute previously set. Instead, you could also provide a specific sorting attribute value (example: "order").

Fetch from a specific context

Whenever you are inside a different NSManagedObjectContext than the default one, you need to fetch the entities from this context.

To do so make sure to simply specify the current context to Magical Record:

class func entityForDestination(destination: String, inContext savingContext: NSManagedObjectContext) -> [Plane] {
	let predicate = NSPredicate(format: "destination == \(destination)")
	let entities = Plane.MR_findAllSortedBy(Plane.sortingAttributeName(), ascending: true, withPredicate: predicate, inContext: savingContext)
	return (entities as? [Plane] ?? [])
}

If you try to fetch from the default context, it will either not work or have side effects.

Magical Record provides much and more functions to let you retrieve your models in a very optimal way.

Retrieve an entity from another context

In case you would like to use an entity fetched from the main context inside another context, you must retrieve this entity again.

let plane = Plane.MR_findFirst()

DKDBManager.saveWithBlock { (savingContext: NSManagedObjectContext) in
	// Executed on background thread
	// Retrieve the `plane` entity from the new (saving) context
	let localPlane = plane?.entityInContext(savingContext)
}

Once you are back on the main thread within the default context, you might need to fetch the entity again:

plane = plane.entityInDefaultContext()