espagram/Espagram/Lesson+Create.m
2012-11-23 23:06:49 +01:00

51 lines
1.9 KiB
Objective-C

//
// Lesson+Create.m
// Palabel
//
// Created by Abel Fokkinga on 1/29/12.
// Copyright (c) 2012 T-consult International vof. All rights reserved.
//
#import "Lesson+Create.h"
@implementation Lesson (Create)
+ (void) addLessonWithTitle:(NSString *) title andSubTitle:(NSString *)subTitle
inTense:(Tense *)tense conjugatedBy:(id <Conjugator>) conjugator inManagedObjectContext:(NSManagedObjectContext *) context
{
Lesson *lesson = nil;
// Check if a lesson with this name already exists for this tense
NSLog(@"Adding Lesson %@ for tense %@ in %@ at context %@", title, tense.tense, [conjugator description], context);
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Lesson"];
// Where clause
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:[NSPredicate predicateWithFormat:@"title = %@", title],[NSPredicate predicateWithFormat:@"tense = %@", tense.tense], [NSPredicate predicateWithFormat:@"conjugator = %@", [conjugator description]],nil]];
// Order by
//request.sortDescriptors = [NSSortDescriptor sortDescriptorWithKey:@"dateAdded" ascending:YES];
NSError *error = nil;
NSArray *lessons = [context executeFetchRequest:request error:&error];
if ( error || [lessons count] > 0) {
NSLog(@"Could not add lesson: %@", error.description);
} else {
NSLog(@"Inserting new lesson in context %@", context);
lesson = [NSEntityDescription insertNewObjectForEntityForName:@"Lesson" inManagedObjectContext:context];
lesson.title = title;
lesson.subTitle = subTitle;
lesson.tense = tense.tense;
lesson.conjugator = [conjugator description];
lesson.dateAdded = [[NSDate alloc] initWithTimeIntervalSinceNow:0];
NSLog(@"Saving context");
[context save:&error];
}
}
@end