Search code examples
core-dataios5nsfetchedresultscontrolleriphone-4nsindexpath

iPhone4 Core Data how to insert a new object with section number?


I'm trying to insert new objects into my core data structure and have them know which section they belong to.

Here's my insert method, I need to add a certain section to the new record.

-(void)insertNewReminderWithSequenceNumber:(int)sequenceNumber
{
    // Create a new instance of the entity managed by the fetched results controller.
    NSManagedObjectContext *context = [self.remindersController managedObjectContext];
    NSEntityDescription *entity = [[self.remindersController fetchRequest] entity];
    Reminder *newManagedObject = (Reminder*)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
    newManagedObject.sequenceNumber = [NSNumber numberWithInt:sequenceNumber];

}

Here's my retrieve method, note that I set the section to zero.

-(Reminder*)getReminderAtIndex:(int)index
{
    NSIndexPath* temp = [NSIndexPath indexPathForRow:index inSection:0];
    Reminder* reminder  = nil;
    @try {
       reminder= [self.remindersController objectAtIndexPath:temp];
    }
    @catch (NSException *exception) {
        NSLog(@"Exception accessing event at index: %i", index);
        return nil;
    }
    @finally {

    }

    return reminder;
}

How can I insert objects into core data to be able to retrieve them by indexPath containing both section number and row number?

Thank you!


Solution

  • Simply use the provided method objectAtIndexPath:

    Reminder *reminder = (Reminder *) [self.fetchedResultsController 
       objectAtIndexPath];
    

    This has nothing to do with how you insert the object into the managed object context. Rather, you will have to specify your sections with the sectionNameKeyPath parameter of your NSFetchedResultsController.