在不同视图控制器上的数组之间移动对象

时间:2014-02-28 01:45:58

标签: objective-c uitableview viewcontroller

我在view controllers中有两个tab bar controller,每个mutable array都有自己的tableviewNSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell]; Candy *item = [[Candy alloc]init]; item = [array1 objectAtIndex:cellIndexPath.row]; SecondViewController *second = [[SecondViewController alloc]init]; [second.array2 addObject:item]; [array1 removeObjectAtIndex:cellIndexPath.row]; [self.tableView deleteRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationLeft]; 。当我按下第一个视图控制器上的行/单元格时,我想将单元格所持有的对象传递给第二个视图控制器,然后将其从第一个视图控制器中删除。

viewDidLoad

这就是我在[super viewDidLoad]; self.tableView.delegate = self; self.tableView.dataSource = self; self.array2 =[[NSMutableArray alloc]init]; 中为第二个控制器(接收控制器)所拥有的:

{{1}}

2 个答案:

答案 0 :(得分:1)

你有两个问题:

首先,你正在分配一个对象而从不使用它(它不是一个bug,但你可以纠正它)。改变这个

Candy *item = [[Candy alloc]init];
item = [array1 objectAtIndex:cellIndexPath.row];

为此:

Candy *item = [array1 objectAtIndex:cellIndexPath.row];

第二步:将此行移至init方法,否则无法使用,因为当您调用[second.array2 addObject:item];时,数组尚未被初始化,并且基本上您正在发送发送给nil的消息。

self.array2 =[[NSMutableArray alloc]init];

答案 1 :(得分:1)

试试这个:

NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
item = [array1 objectAtIndex:cellIndexPath.row];
//Do not init a new SecondViewController here, just to get the second VC
UINavigationController *secondNav = [[self.tabBarController viewControllers] objectAtIndex:1];
SecondViewController *second = [[secondNav viewControllers] objectAtIndex:0];
[second.array2 addObject:item];
[second.tableView reloadData]; //you should reloadData to see data at VC2, if you don't do this later. 

[array1 removeObjectAtIndex:cellIndexPath.row];
[self.tableView deleteRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationLeft];

顺便说一句,init方法将为UIViewControler

调用initWithNibName
相关问题