I’m just getting started with Core Data and am not sure how this works. I basically have a Person entity and an alarm entity. Each person can have many alarms. What I want is to go to a detailViewController of the person object and see their alarms. Because NSSet isn’t sorted, I have a method to return the alarms sorted like so:
- (NSArray *)sortedTimes {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Alarm" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSSortDescriptor *timeDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES selector:@selector(compare:)];
[request setSortDescriptors:@[timeDescriptor]];
NSError *error = nil;
NSArray *objects = [self.managedObjectContext executeFetchRequest:request error:&error];
// Can I do this???
//self.person.alarms = [NSSet setWithArray:objects];
// for (NSManagedObject *obj in objects) {
// NSDate *date = [obj valueForKey:@"time"];
// NSLog(@"date: %@", [date description]);
// }
return objects;
}
What I’m wondering is, in the line self.person.alarms = [NSSet setWithArray:objects]; is that ok? I guess I’m not sure as to what actually is happening. My executeFetchRequest returns an array of the objects I want. Can I just go ahead and assign it to the person entity’s alarm property? I wasn’t sure if there was a relationship from Person->Alarm that I should not be mucking with, or if something like this is perfectly legal. Thanks!
First of all, your fetch request returns all alarms, not only the alarms of
self.person. You have to add an predicate to the fetch request:(assuming that
personis the inverse relationship from the Alarm entity to the Person entity). But you don’t really need a fetch request to get the sorted alarms of a person. A more direct way isNow to your question: The statement
just re-assigns the same set of alarms to the person. This effectively does not change anything, because it is the same set. In particular, it does not guarantee that
self.person.alarmswill now be sorted by time.Remark: It you want to display a table view with the alarms of a person, you can also use a
NSFetchedResultsController(FRC) as table view data source. The advantage of using a FRC is that the table view is automatically updated if objects are inserted, removed or updated.Have a look at the
NSFetchedResultsControllerandNSFetchedResultsControllerDelegatedocumentation which contains all the required code templates.