Kyle Greenlaw
Kyle Greenlaw

Reputation: 737

Reordering UITableViewCells with Core Data TableView

I have a UITableView that is working with Core data for the user o add their own Cells... but i wanted them to be able to reorder the TableViewCells the way they wanted... i use the code now BUT whenever the reorder it, say i went to add another cell, it would return the the regular state... images below if you're lost...

Below is the code:

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
   if (indexPath.row == 0) // Don't move the first row
       return NO;

   return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{

 id ob = [_devices objectAtIndex:destinationIndexPath.row];

        [_devices replaceObjectAtIndex:destinationIndexPath.row withObject:[_devices objectAtIndex:sourceIndexPath.row]];
        [_devices replaceObjectAtIndex:sourceIndexPath.row withObject:ob];
}

Before reorder

During reorder

Adding new cell

After adding the new cell (back to date ordering)

Upvotes: 1

Views: 1443

Answers (1)

Chris Wagner
Chris Wagner

Reputation: 20993

You should add an order property on your entity so that your sort order is persistent.

Then your data source for the table view needs to be sorted by that order key.

It is likely that your _devices array is getting reinitialized with the results of your Core Data fetch request and therefore your modification to the order is lost.

Updated for comment

Assuming you have an entity named Device that is a sub-class of NSManagedObject with a property named order you could do the following.

NSSortDescriptor *orderSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"order" ascending:YES];
[devicesFetchRequest setSortDescriptors:@[orderSortDescriptor]];

Then when you execute your fetch request and capture the results in your _devices array they will be sorted by the order property.

Then in - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath you will need update the order property on the affected entities.

If you move the device from position 5 to position 2 then you need to update the entities from position 2-4 by +1 and the moved entity to 2. This could get inefficient for large data sets quickly but for small data sets it should perform fine.

Upvotes: 2

Related Questions