I have Week model that has Day as child objects. There is "days" relation property in Week model to access all associated Day objects. Day model has duration property.
How can I figure out sum of day's durations for specified Week object? It would be great to have code example how to create a predicate object with @sum function.
Also is it possible to have "calculated" weekDuration property on Week class that given value of sum of related day's durations during fetch? It would be most elegant solution for that problems, but I don't believe that is possible with CoreData.
Use Core Data to save your application's permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. To sync data across multiple devices in a single iCloud account, Core Data automatically mirrors your schema to a CloudKit container.
The next time you need to store data, you should have a better idea of your options. Core Data is unnecessary for random pieces of unrelated data, but it's a perfect fit for a large, relational data set. The defaults system is ideal for small, random pieces of unrelated data, such as settings or the user's preferences.
From the Xcode menu bar, choose Editor > Create NSManagedObject Subclass. Select your data model, then the appropriate entity, and choose where to save the files. Xcode places both class and properties files into your project.
Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores.
Here is an example of how you would setup your query to find only weeks where the sum of the duration of the days is greater than 100.
NSManagedObjectContext *context = ...;
NSManagedObjectModel *model = ...;
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
fr.entity = [model.entitiesByName objectForKey:@"Week"];
//This predicate will be compiled into pure SQL
fr.predicate = [NSPredicate predicateWithFormat:@"[email protected] > 100"];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:fr error:&error];
if (error) {
NSLog(@"ERROR: %@", error);
}
NSLog(@"Results: %@", results);
You can actually implement the computed property in a similiar way, just add this to the NSManagedObject subclass backing your Week entity:
- (NSNumber *) duration {
return [self valueForKeyPath:@"[email protected]"];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With