snapfish
snapfish

Reputation: 175

moving object between arrays on different view controllers

I have two view controllers in a tab bar controller each with their own mutable array and tableview. When I press a row/cell on the first view controller, I want to pass the object that the cell is holding to the second view controller and then delete it from the first view controller.

NSIndexPath *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];

and this is what I have in viewDidLoad for the second controller (receiving controller):

[super viewDidLoad];

 self.tableView.delegate = self;
 self.tableView.dataSource = self;

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

Upvotes: 0

Views: 106

Answers (2)

simalone
simalone

Reputation: 2768

Try this:

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];

BTW, the init method will call initWithNibName for UIViewControler

Upvotes: 1

Merlevede
Merlevede

Reputation: 8170

You have two problems:

First, you're allocating an object and never using it (it's not a bug, but you can correct it). Change this

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

for this:

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

Second: Move this line to your init method, otherwise it won't work, because by the time you call [second.array2 addObject:item]; the array hasn't been initalized, and basically you're sending the message to nil.

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

Upvotes: 1

Related Questions