-
Notifications
You must be signed in to change notification settings - Fork 5
CRUD Entities From JSON
kevindelord edited this page Jun 28, 2016
·
2 revisions
To CRUD new entities from a JSON you need to have your data inside a NSDictionary object.
If your models are correctly configured, the functions primaryPredicateWithDictionary: and updateWithDictionary:inContext: will be called. The manager will either create a new entity or update an existing one.
And then use one of the following functions:
The completion block posses two parameters:
-
entity: AnyObject?
: the CRUDed plane entity -
state: DKDBManagedObjectState
: the state of the object (created, updated, saved or deleted).
Example:
let planeJSON = ["origin":"Paris", "destination":"London"]
Plane.crudEntityWithDictionary(planeJSON, inContext: savingContext, completion: { (entity: AnyObject?, state: DKDBManagedObjectState) in
// The CRUDed plane is referenced in the `entity`.
// Its actual state is described as follow:
switch state {
case .Create: // The entity has been created, it's all fresh new.
case .Update: // The entity has been updated, its attributes changed.
case .Save: // The entity has been saved, nothing happened.
case .Delete: // The entity has been removed.
}
})
If you do not need the completion block and if you assume that the entity will not be deleted, you can use:
let planeJSON = ["origin":"Paris", "destination":"London"]
let plane = Plane.crudEntityWithDictionary(planeJSON, inContext: savingContext)
If the entity has been deleted, the returned value is nil
.
If you have multiple entities inside one array use:
let planesJSON = [["origin":"Paris", "destination":"London"], ["origin":"Tokyo", "destination":"Sydney"]]
let planes = Plane.crudEntitiesWithArray(planesJSON, inContext: savingContext)