Helps you filter insertions, deletions and updates by comparing your JSON dictionary with your Core Data local objects. It also provides uniquing for you locally stored objects and automatic removal of not found ones.
public class func changes(changes: [[String : AnyObject]],
inEntityNamed entityName: String,
localPrimaryKey: String,
remotePrimaryKey: String,
context: NSManagedObjectContext,
inserted: (objectJSON: NSDictionary) -> Void,
updated: (objectJSON: NSDictionary, updatedObject: NSManagedObject) -> Void)
func importObjects(JSON: [[String : AnyObject]], context: NSManagedObjectContext) {
DATAFilter.changes(JSON,
inEntityNamed: "User",
localPrimaryKey: "remoteID",
remotePrimaryKey: "id",
context: context,
inserted: { objectJSON in
let user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context)
user.fillObjectWithAttributes(JSON)
}) { objectJSON, updatedObject in
if let user = updatedObject as? User {
user.fillObjectWithAttributes(JSON)
}
}
}
localPrimaryKey
is the name of the local primary key, for example id
or remoteID
.
remotePrimaryKey
is the name of the key from JSON, for example id
.
Use the predicate to filter out mapped changes. For example if the JSON response belongs to only inactive users, you could have a predicate like this:
let predicate = NSPredicate(format: "inactive == %@", true)
As a side note, you should use a fancier property mapper that does the fillObjectWithAttributes
part for you.
DATAFilter
also provides the option to set which operations should be run when filtering, by default .All
is used but you could also set the option to just .Insert
and .Update
(avoiding removing items) or .Update
and .Delete
(avoiding updating items).
Usage goes like this:
// No items will be deleted here
DATAFilter.changes(JSONObjects,
inEntityNamed: "User",
predicate: nil,
operations: [.Insert, .Update],
localPrimaryKey: "remoteID",
remotePrimaryKey: "id",
context: backgroundContext,
inserted: { objectJSON in
// Do something with inserted items
}, updated: { objectJSON, updatedObject in
// Do something with updated items
})
iOS 7.0
, Core Data
DATAFilter is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'DATAFilter'
Elvis Nuñez, [email protected]
DATAFilter is available under the MIT license. See the LICENSE file for more info.