I just started exploring ios and xcode, and have starting building an app that uses Core Data.
In my model, I have 2 related entities:
- an Exam entity with an examDate and a studyStartDate
- a CalendarItem to plan/ log preparation for an exam.
A part of business logic is: for all dates between studyStartDate and examDate, I want to have a CalendarItem.
So for this, I need code that creates/ deletes CalendarItems every time the the start and end of the date range (in studyStartDate and examDate) change.
In other posts (e.g. here) I read that this type of business logic should go in model (not in controller). So now I need a place inside my model where I can code this.
My question is: where do I create this code? In the subclass of NSManagedObject for the examItem? How do I get access to the ManagedObjectContext in examItem (which I think I need if a insert/ delete other records in my model)? Or do I need to subclass NSManagedObjectContext and build my logic there?
I am really lost here.
UPDATE:
Thanks to the answers below, I followed up on the database manager model - more or less. It feels like the right direction to try keep the ManagedObjects simple, and focused on single entities.
I created a class CalendarManager, which I instantiate once, in appdelegate. It receives ManagedObjectContext. It subscribes to insert/delete notifications in notification-center, and for each new Exam, it sets up Key Value Observers.
As an aside: The KVO are needed to focus on only the date items in the exam. Could not use the NSManagedObjectContextObjectsDidChangeNotification unfortunately. That would run into endless loops: adding/removing a related CalendarItem would also change Exam, which would trigger another loop.
CalendarManager.h
#import <CoreData/CoreData.h>
@interface CalendarManager : NSObject
-(id)initWith:(NSManagedObjectContext *)moc;
@end
CalendarManager.m
#import "CalendarManager.h"
#import "Exam.h" // NSManagedObject subclass
#import "CalendarItem.h" // NSManagedObject subclass
@interface CalendarManager ()
-(void)updateCalendarItemsFor:(Exam*)exam;
-(void)setObserverFor:(Exam*)exam;
-(void)removeObserverFor:(Exam*)exam;
@property NSArray *keyPaths;
@property NSManagedObjectContext *moc;
@end
Works for me this way.