Swift 3 Core Data - NSExpression forFunction: sum: throws error ( could not cast dictionary to Day )
This solves my problem:
let sumRequest: NSFetchRequest<NSFetchRequestResult> = Day.fetchRequest()
Instead of putting Day
as NSFetchRequestResult
, I put NSFetchRequestResult
itself there. Now it's working.
I believe as I set it to a different resultType
it's not [Day]
anymore that gets returned, so that's why I needed to change that to be more generic or something.
xcode8 beta4 not generating the managedObjectContext
The error message reads:
Value of type 'ViewController' has no member 'managedObjectContext'
What this means is that somewhere (your screenshot does not show where) you are attempting to assign a value to a property named managedObjectContext
, on an instance of your ViewController
class. Except that this class doesn't have a property named managedObjectContext
, so Swift complains and doesn't compile.
This is not actually a Core Data question-- it's basic Swift. It would happen for any attempt to assign a value to a nonexistent property.
You probably (again, your screenshot does not provide enough detail to be sure) need to create this property on your view controller class, with type NSManagedObjectContext
.
Parsing NSDictionary result of grouped by fetch request in Core Data
First of all the result of a Core Data fetch is definitely not a JSON object
Second of all be more specific!
Since the return type of the fetch request is clearly dictionary use the generic type to pass NSDictionary
let request = NSFetchRequest<NSDictionary>(entityName: "GuestsTable")
Then cast the type accordingly to the actual type [[String:Any]]
.
var matchedGuests = [[String:Any]]()
...
if let result = try? context.fetch(request) as! [[String:Any]] {
matchedGuests = result
}
Even if an try?
error occurs the forced unwrapped return type will never cause a crash assuming the fetch request is valid.
If you want only the guest names map
the array
let popularGuestNames = matchedGuests.flatMap { $0["guestName"] as? String }
How to sum filtered Core Data in SwiftUI?
I have found similar problem in this question:
Sum of (double) fetch request field
I have modified the code a little and came up with this solution:
import SwiftUI
import CoreData
struct DashboardView: View {
@Environment(\.managedObjectContext) var managedObjectContext
// FetchRequest with predicate set to "after now"
@FetchRequest(entity: NPTransaction.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \NPTransaction.value, ascending: false)], predicate: NSPredicate(format: "date > %@", Date() as NSDate)) var fetchRequest: FetchedResults<NPTransaction>
// sum results using reduce
var sum: Int64 {
fetchRequest.reduce(0) { $0 + $1.value }
}
var body: some View {
NavigationView {
VStack(alignment: .leading) {
HStack {
VStack(alignment: .leading) {
Text("sum")
Text("\(sum)")
.font(.largeTitle)
}
Spacer()
}
.padding()
Spacer()
}.navigationBarTitle("Title")
}
}
}
struct DashboardView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
return DashboardView().environment(\.managedObjectContext, context)
}
}
Core Data - How to fetch an entity with max value property
You set the fetchLimit
to 1
and sort by personId
in descending order. E.g.:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Person"];
fetchRequest.fetchLimit = 1;
fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"personId" ascending:NO]];
NSError *error = nil;
id person = [managedObjectContext executeFetchRequest:fetchRequest error:&error].firstObject;
Using sum aggregate with CoreData
First, this should be a class method. You are fetching arbitrary Operation
instances, so there is no good argument why this should be called in the context of one particular instance.
Second, I think this can be simplified greatly as follows: fetch all operations with the given constraints, then:
let q1Sum = (operations as NSArray).valueForKeyPath("@sum.amount").doubleValue
or, more "swiftly":
let q1Sum = operations.map { $0.amount.doubleValue }.reduce(0, combine: +)
There is no good discernible reason for going into NSExpression
complexities and for using NSDictionaryResultType
, unless you are getting performance issues, which would be highly unlikely.
How to sum a double attribute from CoreData in swift
In your current code, you're attempting to cast logsArray
as an array of doubles when it's in fact an array of NSManagedObject
s. That's why you're getting an error when you attempt to reduce
the array.
To get the sum of the double values associated with your "totalWorkTimeInHours" key in Core Data, you have to access the "totalWorkTimeInHours" key from each NSManagedObject
returned from your fetch request then add them together, ex:
override func viewDidLoad() {
super.viewDidLoad()
//CoreData
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
var fetchRequest = NSFetchRequest(entityName: "Log")
fetchRequest.returnsObjectsAsFaults = false;
var results: NSArray = managedContext.executeFetchRequest(fetchRequest, error: nil)!
var totalHoursWorkedSum: Double = 0
for res in results {
var totalWorkTimeInHours = res.valueForKey("totalWorkTimeInHours") as Double
totalHoursWorkedSum += totalWorkTimeInHours
}
print("Sum = \(totalHoursWorkedSum)")
}
Related Topics
Swift, Pass Data Back from Popover to View Controller
Check for Launching from Uilocalnotification in Swift
Swift Draw Shadow to a Uibezier Path
Xcode 11 Doesn't Recognize Core Data Entity
Dispatchqueue:Cannot Be Called with Ascopy = No on Non-Main Thread
Why Does Filters in Swift Iterate the Collection Twice
Enumerateobjectsusingblock in Swift
Unsafemutablepointer<Uint8> to [Uint8] Without Memory Copy
Swift Struct Doesn't Conform to Protocol Equatable
Collection View Cell Button Not Triggering Action
Uialertcontroller Change Font Color
How to Prove "Copy-On-Write" on String Type in Swift
Swift Tableview Cell Set Accessory Type
Resetting Zone Allocator with Allocations Still Alive
How to Select a Contact with Abpeoplepickernavigationcontroller in Swift
Swift 2.0 Constraintswithvisualformat
An Nsmanagedobject of Class 'Classname' Must Have a Valid Nsentitydescription.' Error