1

首先让我告诉你我想做什么。将数据加载到数组中(从核心数据实体),填充表格视图,如果用户需要,重新排序单元格并更新数组。

就是这样。

我发现了我的问题,我只是不知道如何解决它:

我正在将我的实体数据/属性加载到一个数组中,并用数据填充我的表格视图(下面是问题):

-(void)viewWillAppear:(BOOL)animated{
if (self.context == nil)
{
    self.context = [(RootAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"HandgunAmmo" inManagedObjectContext:self.context];
[request setEntity:entity];
NSError *error;
//PROBLEM!!! the 2 lines below this. 
NSMutableArray *array = [[self.context executeFetchRequest:request error:&error] mutableCopy];
[self setTableArray:array];
[self.ammoTable reloadData];
[super viewWillAppear:YES];
}

所以此时表格视图已加载数据(考虑到cellForRow被调用)

用户移动了几个单元格,我更新数组如下:

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath     *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    // fetch the object at the row being moved
NSString *r = [self.tableArray objectAtIndex:fromIndexPath.row];

    // remove the original from the data structure
[self.tableArray removeObjectAtIndex:fromIndexPath.row];

    // insert the object at the target row
[self.tableArray insertObject:r atIndex:toIndexPath.row];

[self.ammoTable reloadData];

}

如您所见,重新排序数组的代码应该可以工作。

But, in the viewWillAppear method, I am loading the entities attributes into the array again and using it to populate the table view which is the problem. When i update the array, its not updating the order of the objects inside of the entity. Does anyone know how to update that? I would really appreciate it!

Thank you!

4

1 回答 1

2

The managedObjects represented in the array have no sense of their position in the array. Therefore rearranging their place is changing their visible position but not their position in the database.

If you want to sort then you need to do some things:

  1. Have your NSFetchRequest include an NSPredicate that sorts on a sort field
  2. Have your moveRowAtIndexPath method not only reposition the data but also update the sort field to reflect their new position
  3. Save the updated records to the database so that the next fetch will have the correct sort.

If you already have a fetchResultsController you can forgo the array and just use:

NSManagedObject *ammo = [fetchedResultsController objectAtIndexPath:fromIndexPath];

To get an reference to the current object.

于 2013-03-06T03:10:01.173 回答