CoreData数据库查询Swift2.1

数据库查询 返回 符合条件的属性的总数或平均值等

     
    let fetchRequest = NSFetchRequest(entityName: "Venue")
        fetchRequest.resultType = .DictionaryResultType
        
        let sumExpressionDesc = NSExpressionDescription()
        //添加key方便从fetchrequest获取数据 
        sumExpressionDesc.name = "sumDeals"
        //sum: 为NSExpression 默认函数  计算总数
        //specialCount 数据库对象 Venue 的一个属性
        sumExpressionDesc.expression = NSExpression(forFunction: "sum:", arguments: [NSExpression(forKeyPath: "specialCount")])
        sumExpressionDesc.expressionResultType = .Integer32AttributeType
        fetchRequest.propertiesToFetch = [sumExpressionDesc]
        
        do {
            let results =
            try coreDataStack.context.executeFetchRequest(fetchRequest) as! [NSDictionary]
            let resultDict = results.first!
            let numDeals = resultDict["sumDeals"]
            numDealsLabel.text = "\(numDeals!) total deals"
        } catch let error as NSError {
            print("Could not fetch \(error), \(error.userInfo)")
        }

NSExpression()方法添加 操作函数名 默认支持的函数可查看此类
使用fetchRequest.propertiesToFetch 查询数据库

你可能感兴趣的:(CoreData数据库查询Swift2.1)