I have managed objects that I access using fetch requests.
Writing the fetch request again and again every single time I want the objects is tedious, so I made myself a convenience method that contains the fetch request.
My object is WeekDay, and to retrieve all WeekDay objects I created the following method in WeekDay class:
+ (NSArray *)allWeekDaysWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"WeekDay"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"day" ascending:YES];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
return [managedObjectContext executeFetchRequest:fetchRequest error:nil];
This code works, yet I do feel that something is wrong.
Moving the managedObjectContext as a parameter every single time, although I have only one managedObjectContext is just annoying. I read that Apple recommends View Controllers to pass the managedObjectContext like this, but is this recommendation still applied to non-ViewController classes?
Is there a naming convention for such methods? I just really really smell that this piece of code is tedious every time I use this method.
What you have developed here is fine. You should pass in the context so that when you add another context you won't need to refactor. You can roll these into a helper class if you want but I tend to put them into the data object classes themselves. It makes it very clear what is happening.