首先让我告诉你我想做什么。将数据加载到数组中(从核心数据实体),填充表格视图,如果用户需要,重新排序单元格并更新数组。
就是这样。
我发现了我的问题,我只是不知道如何解决它:
我正在将我的实体数据/属性加载到一个数组中,并用数据填充我的表格视图(下面是问题):
-(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!