small medium large xlarge

Back to: All Forums  Core Data
Generic-user-small
07 Nov 2011, 00:49
Greg Robertson (21 posts)

What is the best way to create and handle a sequential relationship in CoreData, by this I mean a relationship between attributes in sequential entities.

For example if I have an entity ‘Book’ with a to many relationship with another Entitiy ‘BookChapters’ with three attributes: ‘chapterNumber’, ‘pages’ and ‘runningTotal’.

Is there a way I can automagically calculate the running total of pages by adding all the pages previously but not after? A short cut would be to add the runningTotal of the previous chapter with the pages of the chapter but does it make sense to do it this way?

Should I do this in the class, if so how would I ensure it is saved?

Thanks

Greg

Avatarsmall_pragsmall
11 Dec 2011, 20:46
Marcus S. Zarra (284 posts)

There is not an automatic way to this but it is pretty simple in code.

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[self entity]];
[request setPredicate:[NSPredicate predicateWithFormat:@"book == %@ && chapterNumber < %i", [self book], [[self chapterNumber] integerValue]]];

NSError *error = nil;
NSArray *previousChapters = [[self managedObjectContext] executeFetchRequest:request error:&error];
NSAssert1(error && !previousChapters, @"Error fetching: %@", error);

id result = [previousChapters valueForKeyPath:@"@sum.pages"];

That was typed into the browser so there may be minor errors but it gives you the idea :)

You can also store this calculated value and then just recalculate it on each fetch if you want.

You must be logged in to comment