Skip to content

Setup For Automatic CRUDing

kevindelord edited this page Jul 4, 2016 · 6 revisions

The automatic CRUD process requires 2 functions in your model classes.

Use the extended files generated by Xcode to add the following methods in your model classes.

The two following functions will be automatically called by the CRUD process.

Override this function to create a predicate used in the CRUD process to find the right entity corresponding to the given dictionary. The manager will then create a new entity or update/delete an existing one.

The predicate should be created depending on the given dictionary and should match only one database entity.

For example:

override class func primaryPredicateWithDictionary(dictionary: [NSObject:AnyObject]?) -> NSPredicate? {
	// Return a valid predicate to match one specific entity.
	// For example, a plane could be fetched by its origin and destination attributes.
	let origin = GET_STRING(dictionary, "origin")
	let destination = GET_STRING(dictionary, "destination")
	return NSPredicate(format: "origin == %@ && destination == %@", origin, destination)
}

If you need the CRUD process to only take the first entity created (if any) and update it (only ONE entity will ever be created):

return nil

If you need the CRUD process to always create a new entity (default behavior):

return NSPredicate(format: "FALSEPREDICATE")

If you need the CRUD process to use a random entity in the database (that's dangerous):

return NSPredicate(format: "TRUEPREDICATE")

Override to update the current entity with a given dictionary.

Without this function the attributes of the entity will never be set nor updated.

The given dictionary object is the same one that has been used to start the CRUD process.

Remark: The super function should be called.

override func updateWithDictionary(dictionary: [NSObject : AnyObject]?, inContext savingContext: NSManagedObjectContext) {
	super.updateWithDictionary(dictionary, inContext: savingContext)
	// Update attributes
	self.origin 		= GET_STRING(dictionary, "origin")
	self.destination 	= GET_STRING(dictionary, "destination")
}

PS: the GET_STRING function is taken from the DKHelper library.