首先让我告诉你我想做什么。将数据加载到数组(来自核心数据实体),填充表视图, 如果用户想要,重新排序单元格并更新数组。
多数民众赞成。
我发现了我的问题,我只是不知道如何解决它:
我正在将我的实体数据/属性加载到一个数组中,并用数据填充我的tableview (以下是问题):
-(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];
}
正如您所看到的,重新排序数组的代码应该可行。
但是,在viewWillAppear
方法中,我再次将实体属性加载到数组中并使用它来填充表视图,这就是问题所在。当我更新数组时,它不会更新实体内部对象的顺序。有谁知道如何更新?我真的很感激!
谢谢!
答案 0 :(得分:2)
数组中表示的managedObjects不知道它们在数组中的位置。因此,重新安排他们的位置是改变他们的可见位置,而不是他们在数据库中的位置。
如果你想排序,那么你需要做一些事情:
NSFetchRequest
包含在排序字段中排序的NSPredicate moveRowAtIndexPath
方法不仅可以重新定位数据,还可以更新排序字段以反映新的位置如果你已经有了fetchResultsController,你可以放弃数组并使用:
NSManagedObject *ammo = [fetchedResultsController objectAtIndexPath:fromIndexPath];
获取对当前对象的引用。