DATAFilter 1.0.1

DATAFilter 1.0.1

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Sep 2016
SPMSupports SPM

Maintained by Elvis Nuñez.



DATAFilter

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.

The magic

public class func changes(changes: [[String : Any]],
      inEntityNamed entityName: String,
      localPrimaryKey: String,
      remotePrimaryKey: String,
      context: NSManagedObjectContext,
      inserted: (JSON: [String : Any]) -> Void,
      updated: (JSON: [String : Any], updatedObject: NSManagedObject) -> Void)

How to use

func importObjects(JSON: [[String : Any]], context: NSManagedObjectContext) {
    DATAFilter.changes(JSON,
                       inEntityNamed: "User",
                       localPrimaryKey: "remoteID",
                       remotePrimaryKey: "id",
                       context: context,
                       inserted: { JSON in
            let user = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context)
            user.fillObjectWithAttributes(JSON)
        }) { JSON, updatedObject in
            if let user = updatedObject as? User {
                user.fillObjectWithAttributes(JSON)
            }
    }
}

Local and remote primary keys

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.

Predicate

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.

Operations

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:

DATAFilter.changes(JSONObjects,
    inEntityNamed: "User",
    predicate: nil,
    operations: [.Insert, .Update],
    localPrimaryKey: "remoteID",
    remotePrimaryKey: "id",
    context: backgroundContext,
    inserted: { JSON in
        // Do something with inserted items
    }, updated: { JSON, updatedObject in
        // Do something with updated items
})

Requirements

iOS 7.0, Core Data

Installation

DATAFilter is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'DATAFilter'

Author

SyncDB, [email protected]

License

DATAFilter is available under the MIT license. See the LICENSE file for more info.