Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

iphone - How to use @sum with CoreData

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]"];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...