michaelarmstrong / SuperRecord

A small set of utilities to make working with CoreData and Swift a bit easier.
MIT License
366 stars 27 forks source link

Added more complex NSPredicate and predicate builder #8

Closed PGLongo closed 9 years ago

PGLongo commented 9 years ago

Added predicateBuilder that create a NSPredicate from 3 parameters:

  1. Attribute name
  2. Attribute value (any object)
  3. NSPredicateOperator

enum NSPredicateOperator : String {
    case And = "AND"
    case Or = "OR"
    case In = "IN"
    case Equal = "=="
    case NotEqual = "!="
    case GreaterThan = ">"
    case GreaterThanOrEqual = ">="
    case LessThan = "<"
    case LessThanOrEqual = "<="
}

    class func predicateBuilder(attribute: String!, value: AnyObject, predicateOperator: NSPredicateOperator ) -> NSPredicate? {
        var predicate = NSPredicate(format: "%K \(predicateOperator.rawValue) $value", attribute)
        predicate = predicate?.predicateWithSubstitutionVariables(["value" : value]);
        return predicate
    }

For example:

NSPredicate.predicateBuilder("level", value: 16, predicateOperator: .LessThan)
NSPredicate(format: "level < 16")
...
NSPredicate.predicateBuilder("name", value: "Charmender", predicateOperator: .Equal)
NSPredicate(format: "name == \"Charmender\"")

Using predicateBuilder I have improved findFirstOrCreateWithAttribute, now it works with all value and not only with strings

class func findFirstOrCreateWithAttribute(attribute: String!, value: AnyObject!, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, handler: ((NSError!) -> Void)! = nil) -> NSManagedObject {
        var predicate = NSPredicate.predicateBuilder(attribute, value: value, predicateOperator: .Equal)
        return findFirstOrCreateWithPredicate(predicate, context: context, handler)
}

I have also added a new init method to allow the creation of more complex NSPredicate (the kind of firstCondition AND ( secondCondition OR thirdCondition)

 convenience init?(firstPredicate : NSPredicate, secondPredicate: NSPredicate, predicateOperator: NSLogicOperator ) {
            self.init(format: "(\(firstPredicate)) \(predicateOperator.rawValue) (\(secondPredicate))")
}
michaelarmstrong commented 9 years ago

Fantastic, can you merge develop into this branch so its mergable. Thanks

PGLongo commented 9 years ago

Fixed!