Reputation: 55
I have a table populated by an NSMutableArray. The user has the ability to reorder the cells (rows) how they want. I want to insert the records into the database from the array inheriting the reordered sequence.
So say the table loaded: row 1 row 2 row 3 row 4
And the user reorders to: row 4 row 2 row 1 row 3
I want to push the data to the database with the reordered sequence. However when I insert all four rows via looping after reordering the rows via UITableView, the order goes into the database with the original order (not the rearranged order).
Is there a way to refresh the array from the reordered table?
Upvotes: 2
Views: 627
Reputation: 1369
Your records should have an 'order' field and store it to database. When loading from database you should sort the records with the field.
EDIT: the code below illustrates the idea
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
if (destinationIndexPath.row > sourceIndexPath.row) {
for (NSInteger row = sourceIndexPath.row + 1; row <= destinationIndexPath.row; ++row) {
Record* record = array[row];
record.row = [NSNumber numberWithInt:record.row.intValue - 1];
}
} else if (destinationIndexPath.row < sourceIndexPath.row) {
for (NSInteger row = destinationIndexPath.row; row < sourceIndexPath.row; ++row) {
Record* record = array[row];
record.row = [NSNumber numberWithInt:record.row.intValue + 1];
}
}
Record* record = array[sourceIndexPath.row];
record.row = [NSNumber numberWithInt:destinationIndexPath.row];
[array removeObjectAtIndex:sourceIndexPath.row];
[array insertObject:record atIndex:destinationIndexPath.row];
[self save];
}
- (void)loadFromCoreData {
NSFetchRequest* request = [[NSFetchRequest alloc] init];
NSEntityDescription* entity = [NSEntityDescription entityForName:@"Record" inManagedObjectContext:_managedObjectContext];
request.entity = entity;
NSSortDescriptor* sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"row" ascending:YES];
NSArray* sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
request.sortDescriptors = sortDescriptors;
NSError* error;
array = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
}
Upvotes: 2
Reputation: 313
I think a better way is to store the row number as a field along with other cell data. This way whenever you want to show the data again you have the row number to construct user's order.
Upvotes: 0