views:

29

answers:

2

I have a Core Data app that works to add or remove one of a Client's many Appointments with buttons bound in IB to my appointments ArrayController. The appointments content is derived from whichever Client is selected in a feed list. I wish to use a SegmentedControl, and as far as I could tell, this requires I programmatically add and remove the objects in appointments. I have successfully managed to add an Appointment using Marcus Zarra’s code from his book Core Data on p54, but I am at a loss to remove a selected Appointment. I am using a custom table cell, which I suspect might be complicating matters.

In short, I wish to programmatically achieve the equivalent of an ArrayController’s remove: method on a selected object.

Can anyone help, please?

A: 

Get the current selection from you ArrayController bound to your UI

- (NSArray *)selectedObjects

delete those objects using the context

-(void) deleteObject:(NSManagedObject*) object

Sample:

NSArray* objectsToDelete = [NSArray arrayWithArray:[arrayController selectedObject]];
for (NSManagedObject* objectToDelete in objectsToDelete)
{
  [arrayController.managedObjectContext deleteObject:objectToDelete];
}
Martin Brugger
A: 

Thanks, Martin. My code eventually looked like this.

-(IBAction) notesEditorSegClicked:(id)sender{
    int clickedSegment = [sender selectedSegment];
    switch (clickedSegment) {
        case 0:{ // add new object
            NSManagedObject *newNote = [NSEntityDescription
            insertNewObjectForEntityForName:@"Note"
            inManagedObjectContext:notes.managedObjectContext];
            [notes addObject:newNote];
            break;
        }
        case 1:{ // delete selected object
            NSArray *objectsToDelete = [notes selectedObjects];
            for (NSManagedObject* objectToDelete in objectsToDelete){
                [notes.managedObjectContext deleteObject:objectToDelete];
            }
            break;
        }
        case 2:{// close view
            [self loadClientSummary:sender];
            break;
        }
    }
}
Lachlan Scott