0
votes

I have a UITableView that contains Core Data objects. When you click on a row, you get taken to another view controller with an option to delete the image among other things. How would I delete a specific object core data based on the row I selected. So say I would selected an image and then clicked the delete button in the presented view controller, it would delete the image I selected only.

EDIT added code for the delete in DetailedViewController

NSError *error = nil; 
[self.managedObjectContext deleteObject:self.managedObject]; 

// REMOVE THIS LINE NO NEED TO CALL SAVE TWICE
//[self.managedObjectContext save:&error]; 

if (![self.managedObjectContext save:&error]) { 
NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
abort(); 
} else { 
NSLog(@"Video and Photo Deleted"); 
}
1
Show the code are you using to populate the UITableView with data and how you are passing the object to the detailed view controller.Duncan Groenewald

1 Answers

0
votes

Usually you would use something like this if you were deleting in the UITableView and assuming you are using a fetchedResultsController.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        if (editingStyle == UITableViewCellEditingStyleDelete) {
           NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
           [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

        }
    }
}

However if you are in some detailedViewController then assuming you passed the managedObjectContext and the managedObject to this detailedViewController (self) you would just use this. Once again assuming you are using fetchedResultsController in conjunction with the UITableView so deletes are correctly reflected in the UITableView.

   [self.managedObjectContext deleteObject:self.managedObject];

You can pass these to the detailedViewController by creating properties and setting the properties like so

@interface DetailedViewController: UIViewController

@property (strong, nonatomic) NSManagedObject *detailItem;
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

@end

and after creating the detailedViewController set the properties as shown below

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];

    // Code to create detailed view and set properties
     DetailedViewController *detailedViewController = [DetailedViewController alloc] ...;
     detailedViewController.managedObjectContext = self.managedObjectContext;
     detailedViewController.managedObject = object;

     [self.navigationController pushViewController:detailViewController animated:YES];
}