我创建了一个NSMutableArray类别。我只想移动我的数组中的对象,当它们在我的表视图中移动时。这是我的类别:
- (void)moveObjectFromIndex:(NSUInteger)from toIndex:(NSUInteger)to
{
if (to != from) {
id obj = [self objectAtIndex:from];
[self removeObjectAtIndex:from];
if (to >= [self count]) {
[self addObject:obj];
} else {
[self insertObject:obj atIndex:to];
}
}
}
在我的视图控制器中,我打电话:
- (void)tableView:(UITableView *)table moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
[self.tableArray moveObjectFromIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
[self.ammoTable reloadData];
}
但阵列似乎并没有在其周围移动物体。这可能是什么原因?我跟着这个tutorial。它应该工作,如果有人可以告诉问题,请高兴我的原因。非常感谢!
修改
我也尝试过下面的代码,遗憾的是它不起作用:
- (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];
}
再次编辑
CellForRow:
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString * identifier = @"identifier";
self.cell = [tableView dequeueReusableCellWithIdentifier:identifier];
HandgunAmmo *handgunAmmo = [self.tableArray objectAtIndex:indexPath.row];
self.cell.brandLabel.text = handgunAmmo.brand;
self.cell.caliberLabel.text = handgunAmmo.caliber;
self.cell.numberOfRoundsLabel.text = handgunAmmo.numberOfRounds;
return self.cell;
}
更新
-(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;
NSMutableArray *array = [[self.context executeFetchRequest:request error:&error] mutableCopy];
[self setTableArray:array];
[self.ammoTable reloadData];
[super viewWillAppear:YES];
}
//上面,我加载我的核心数据。
我不打电话
-(void)viewWillDisappear;