title: iOS - Core Data - Delete records using relationships and fetch request
body: <p><strong>Overview:</strong></p>
  
  <p>I have an iOS project in which I am using core data</p>
  
  <ul>
  <li>I have an <code>Employees</code> entity and a <code>Department</code> entity.</li>
  <li>1 department can contain many employees </li>
  <li>So the entity <code>Department</code> has a "to many" relationship with the entity <code>Employees</code>, the relationship is called <code>employees</code> and the reverse relationship is called <code>whichDepartment</code></li>
  </ul>
  
  <p><strong>Aim-1:</strong></p>
  
  <p>I want to delete all the employees in a specific department </p>
  
  <p><strong>Questions:</strong></p>
  
  <p>a) is the following correct, or would it cause mutation or some problems ?</p>
  
  <p>b) is this is the correct way to do it ?</p>
  
  <p><strong>Pls Note</strong> - <code>removeEmployees</code> is a method that was auto generated while creating the subclasses of the entities</p>
  
  <pre><code>- (void) deleteAllEmployeesForDepartment: (Department*) requestedDepartment
  {
      [requestedDepartment removeEmployees:requestedDepartment.employees];
  }
  </code></pre>
  
  <p><strong>Aim-2:</strong></p>
  
  <ul>
  <li>I want to delete the employees based on some condition</li>
  <li>I am deleting objects inside a fast enumeration loop for the fetched records</li>
  </ul>
  
  <p><strong>Questions:</strong> </p>
  
  <p>c) Is the following correct, or would it cause some mutation ?</p>
  
  <p>d) Is it like modifying the object in fast enumeration ?</p>
  
  <p>e) Is there a better way to do it ?</p>
  
  <p><strong>Pls Note</strong> - <code>removeEmployees</code> is a method that was auto generated while creating the subclasses of the entities</p>
  
  <pre><code>- (void) deleteAllType1EmployeesWithDepartment: (Department*) requestedDepartment
  { 
      fetchRequest.predicate = [NSPredicate predicateWithFormat:@"type == %i AND whichDepartment ==%i", 1, requestedDepartment.departmentID];
  
      NSError *error;
      NSArray *listOfEmployeesToBeDeleted = [self.managedObjectContext executeFetchRequest:fetchRequest error:&amp;error];    
  
      for(Employees *currentEmployee in listOfEmployeesToBeDeleted)
      {       
         [self.managedObjectContext deleteObject:currentEmployee];
      }
  }
  </code></pre>