michaelarmstrong/SuperRecord — pull request #8 by PGLongo (2014-12-14 16:44:32+00:00)
Title: Added more complex NSPredicate and predicate builder

Added predicateBuilder that create a NSPredicate from 3 parameters:
1. Attribute name
2. Attribute value (any object)
3. NSPredicateOperator

```swift

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:

```swift
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

```swift
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)
```swift
convenience init?(firstPredicate : NSPredicate, secondPredicate: NSPredicate, predicateOperator: NSLogicOperator ) {
self.init(format: "(\(firstPredicate)) \(predicateOperator.rawValue) (\(secondPredicate))")
}
```