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 operations #5

Closed PGLongo closed 9 years ago

PGLongo commented 9 years ago

I have added some functions to NSManagedObject:

  1. Count
  2. Sum
  3. Max
  4. Min
  5. Average

Count

class func count(context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, predicate : NSPredicate?, error: NSErrorPointer) -> Int {
            var entityName : NSString = NSStringFromClass(self)
            var fetchRequest = NSFetchRequest(entityName: entityName);
            fetchRequest.includesPropertyValues = false
            fetchRequest.includesSubentities = false
            fetchRequest.predicate = predicate
            fetchRequest.propertiesToFetch = [];
            return context.countForFetchRequest(fetchRequest, error: error)
    }

is more correct and efficient than

class func countWithPredicate(predicate: NSPredicate!, context: NSManagedObjectContext = SuperCoreDataStack.defaultStack.managedObjectContext!, completionHandler handler: ((NSError!) -> Void)! = nil) -> Int {
            let results = findAllWithPredicate(predicate, context: context, completionHandler: handler)
            return results.count
}

All other functions use NSExpression to compute sum, min, avg, max, min of one ore more field of the NSManagedObject