specialone
specialone

Reputation: 130

Objective C - Passing JSON data from Tableview to another View Controller

JSON Data:

({

    CustDisplayName = "John Doe";
    CustID = 2;
},
    {
    CustDisplayName = "Jane Doe";
    CustID = 21;
})

Displaying the data on tableview like a contact list is working and also the segue(Push) from cell to other view.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath 
*)indexPath {
    [self performSegueWithIdentifier:@"pushDetailView" sender:indexPath];
}

Now I am passing data through prepareForSegue

if ([[segue identifier] isEqualToString:@"pushDetailView"]) {
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];

    NSLog(@"%@", indexPath);
}

The log just shows 0,1,2,3 which is not what I want. I am not sure what is the best way to approach.

  1. Select Row get CustID and do another request on another view's viewDidLoad?
  2. Select Row get that Array and transfer the string to another view?

I am new to iOS development, I hope somebody can help.

Upvotes: 0

Views: 1114

Answers (3)

Imotep
Imotep

Reputation: 2056

Let's say your data source is a NSArray filled with Customer objects.

First, create a Customer property in your detail viewController:

@property (nonatomic,strong) Customer customer;

Then, you have to set this property when selecting a row. To do that use the prepareForSegue method:

-(void) prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender
{
   if ([[segue identifier] isEqualToString:@"pushDetailView"]) {
      DetailViewController*destination= segue.destinationviewcontroller;
      NSIndexPath* indexPath = [tableView indexPathForCell:sender];
      destination.customer = datasource[indexPath.row];
   }
}

Make sure that when you call performSegue you set the cell as the sender. A way to make sure it is is to create your segue from a storyboard and not perform it manually.

You may also want to use this to easily parse your JSON: https://github.com/icanzilb/JSONModel/

Upvotes: 0

Chengappa C D
Chengappa C D

Reputation: 1891

I guess what you need is indexPath.row instead of indexPath

Upvotes: 1

gabbler
gabbler

Reputation: 13766

In your destination ViewController's head file, define a property of type NSDictionary named dict. And parse your Json data to an array, which has NSDictionary objects.

if ([[segue identifier] isEqualToString:@"pushDetailView"]) {
   UIViewController *controller = segue.destinationviewcontroller;
   controller.dict = [array objectAtIndex:indexPath.row].
}

Upvotes: 0

Related Questions