Friday, April 24, 2026
HomeiOS Developmentios - How do I exploit a NSFetchRequest with an NSExpression and...

ios – How do I exploit a NSFetchRequest with an NSExpression and .dictionaryResultType as a SwiftUI @FetchRequest?

[ad_1]

I’ve a mannequin with two entities: Class and Transaction (simplified)

Class
--------
title: String
transactions: Transaction[]

Transaction
-----------
title: String
quantity: Double
date: Date
class: Class

They’re one-to-many so one class can maintain a number of transactions. I’m making an attempt to sum up the whole worth of all Transactions inside a class and inside a given date body. For instance, I wish to know all transactions from march 2022 within the class “Meals”. I’ve provide you with this (at present solely fetching from the previous 30 days)

  let sumExpression = NSExpressionDescription()
  let keypathAmount = NSExpression(forKeyPath: "quantity")
  sumExpression.expression = NSExpression(forFunction: "sum:", arguments: [keypathAmount])
  sumExpression.title = "sum"
  sumExpression.expressionResultType = .doubleAttributeType
  
  let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Transaction")
  let adjustedDate = Calendar.present.date(byAdding: .day, worth: -30, to: Date()) ?? Date()
  let datePredicate = NSPredicate(format: "date > %@", adjustedDate as CVarArg)
  request.predicate = NSCompoundPredicate(
    sort: .and,
    subpredicates: [datePredicate, NSPredicate(format: "category == %@", category)]
  )
  request.propertiesToFetch = [sumExpression]
  request.includesPendingChanges = false 
  request.returnsObjectsAsFaults = false
  request.resultType = .dictionaryResultType
  request.returnsDistinctResults = true

  do {
    let outcomes = strive moc.fetch(request)
    let resultMap = outcomes[0] as! [String:Double]
    return resultMap["sum"] ?? 0.0
  } catch let error as NSError {
    NSLog("Error when summing quantities: (error.localizedDescription)")
  }

Since I exploit the @Atmosphere(.managedObjectContext) var moc I can not use the fetch request within the init() because the atmosphere just isn’t accessible but. So proper now I am doing all this within the onAppear() of the view physique. In stated view, I’ve an @ObservedObject of the at present chosen Class. This in fact doesn’t replace when the transactions change (for instance when a brand new one will get added). I cannot use a @FetchRequest and initialize it with the above NSFetchRequest as a result of Xcode throws

‘NSFetchedResultsController doesn’t help each change monitoring and fetch request’s with NSDictionaryResultType’

How do I circumvent this? What’s one of the simplest ways to fetch the sum of a filtered relationships attribute in SwiftUI? How do I leverage the existence of the @ObservedObject class to retry the fetch request when a change is happening?

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments