Problems sending NSString variables to a ViewController before it is pushed - iphone

I am having problems sending along 2 NSString variables to a view controller right before it is pushed.
here is some relevent code for pushing the controller:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
CommentsViewController *c = [[CommentsViewController alloc] initWithNibName:#"CommentsView" bundle:nil];
c.subreddit = subreddit;
c.redditId = [[[list objectAtIndex:indexPath.row] objectForKey:#"data"] objectForKey:#"id"];
c.title = [[[list objectAtIndex:indexPath.row] objectForKey:#"data"] objectForKey:#"title"];
[self.navigationController pushViewController:c animated:YES];
[c release];
NSLog(#"subreddit: %#", subreddit);
NSLog(#"redditId: %#", [[[list objectAtIndex:indexPath.row] objectForKey:#"data"] objectForKey:#"id"]);
}
note that printing out the variables via NSLog works as expected.
also, the c.title assignment seems to work fine, as i can see the title text on the pushed controller.
here(not just here, anywhere) is where i am finding (null) when printing the corresponding variables which i have assigned:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"subreddit: %#", subreddit);
NSLog(#"redditId: %#", redditId);
}
2010-12-30 20:06:17.108 RedditReader[1073:307] subreddit: (null)
2010-12-30 20:06:17.131 RedditReader[1073:307] redditId: (null)
subreddit has property set as: #property (nonatomic, retain) NSString *subreddit;
Why can't i seem to assign these values correctly so i can use them in the pushed view controller?
How can i assign these values so i can use them in the pushed view controller?

It seems like your viewDidLoad gets called before the variables are set (I don't use nib files so I can't say for sure...). You could make an init method that receives those variables, like this:
- (id)initWithTitle:(NSString *)aTitle reddit:(NSString *)aReddit ... {
self.title = aTitle;
// ...
if (self = [super initWithNibName:#"CommentsView" bundle:nil]) {
// ...
}
return self;
}
Hope this helps!

Override viewWillAppear and you should see your populated variables, viewDidLod is called when uniting from the nib

Related

Why is my delegate method not called?

this is probably simple but I'm stuck!
Basically I have a parent and child view controller, and I'm trying to pass data from the child to the parent.
//Child VC interface
#protocol ANSearchGetawayFilterDelegate
-(void)selectedCell:(NSString *)cellTitle;
#end
#interface ANSearchGetawayFilterViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>
{
NSString* cellTitle;
}
#property (nonatomic, assign) id<ANSearchGetawayFilterDelegate> delegate;
#end
//Child VC implementation
#implementation ANSearchGetawayFilterViewController
#synthesize delegate = _delegate;
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
cellTitle = selectedCell.textLabel.text;
[[self delegate] selectedCell:cellTitle];
[self dismissModalViewControllerAnimated:YES];
}
//Parent VC interface
#import "ANSearchGetawayFilterViewController.h"
#interface ANGetawayFilterViewController : UIViewController <ANSearchGetawayFilterDelegate>
{
NSString* _cellText;
}
//Parent VC Implementation
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
ANSearchGetawayFilterViewController *search = [[ANSearchGetawayFilterViewController alloc] init];
search.delegate = self;
}
return self;
}
//delegate method
-(void)selectedCell:(NSString *)cellTitle
{
_cellText = cellTitle;
NSLog(#"cell text %#", _cellText);
}
the delegate method is never called and when is NSLog the _cellText else where it comes up as null...what am I doing wrong? Thanks!
You are most likely creating a new instance of ANSearchGetawayFilterViewController when you present it and not configuring the delegate on it.
When you called
ANSearchGetawayFilterViewController *search = [[ANSearchGetawayFilterViewController alloc] init];
search.delegate = self;
you created an instance of ANSearchGetawayFilterViewController and then set the delegate up correctly, but you never stored this instance of ANSearchGetawayFilterViewController anywhere. So later on when you come to present it you call again
ANSearchGetawayFilterViewController *search = [[ANSearchGetawayFilterViewController alloc] init];
which gives you a completely different instance, which you then need to configure again. For example
ANSearchGetawayFilterViewController *search = [[ANSearchGetawayFilterViewController alloc] init];
ANSearchGetawayFilterViewController *search1 = [[ANSearchGetawayFilterViewController alloc] init];
NSLog(#"%d", search1 == search);
#=> 0
To fix update your code to be
- (BOOL)textFieldShouldBeginEditing:(UITextField*)textField;
{
BOOL shouldBeginEditing = YES;
NSLog(#"text field should begin editing");
ANSearchGetawayFilterViewController *myANSearchGetawayFilterViewController = [[[ANSearchGetawayFilterViewController alloc] init] autorelease];
myANSearchGetawayFilterViewController.delegate = self; // <--- configure the delegate
[self presentModalViewController:myANSearchGetawayFilterViewController animated:YES];
[self closeAllPickers];
return shouldBeginEditing;
}
I wouldn't make it an ivar as the likelihood is you will present this viewController momentarily just to select some data and then get rid of it, so it is probably safe to discard it and make a new one each time.
Au contraire, the delegate method is being called (hence the NSLog()). However, _cellText is (null) because the value being passed in is nil, ergo selectedCell.textLabel.text.
Firstly, are you sure that the -selectedCell method is being called?
You can do this by putting an NSLog() before or after -tableViewDidSelectRow...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
...
NSLog(#"TABLEVIEW DID SELECT ROW BEFORE -> %# <-", cellTitle);
[[self delegate] selectedCell:cellTitle];
NSLog(#"TABLEVIEW DID SELECT ROW DELEGATE CALLED");
...
}
Also, you might want to do some cleanup (optional)
Firstly, you are leaking in your initialisation method. Either set the ANGetawayFilterViewController as a property of the parent class using the delegate, or release it after you set the delegate.
Secondly, in the -tableViewDidSelectRow, your code assumes that the delegate has the -selectedCell method coded. If you don't have the method implemented, then the application will result in a crash. You can prevent this by checking to see if the delegate -respondsToSelector...:
if ([self.delegate respondsToSelector:#selector(selectedCell:)]) {
[self.delegate selectedCell:cellTitle];
}
Thirdly, the method of which is being called by the delegate to notify the parentViewController doesn't follow the general schema that delegate methods use, with the exception of -numberOfRowsInSection (UITableViewDelegate). Your method should contain the actual ANFilterGetawayViewController instance too:
- (void) filterGetawayViewController:(ANSearchGetawayFilterViewController *) controller didSelectCellWithTitle:(NSString *) title {
...
}
It can be called as such:
[self.delegate filterGetawayViewController:self didSelectCellWithTitle:cellTitle];
Are you using ARC? Because when the init function ends, your object (and it's reference to the delegate) are cleaned up. What happens if you make the search variable a global one (defining it in your header and initializing it in your code)?
Assuming you are using ARC:
You need to make a retained #property for your ANSearchGetawayFilterViewController instance. It will have been released by ARC by the time the delegate method is called. Do something like this.
#property (strong, nonatomic) ANSearchGetawayFilterViewController *search;
...
#synthesize search = _search;
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
self.search = [[ANSearchGetawayFilterViewController alloc] init];
self.search.delegate = self;
}
return self;
}
Not related to your problem, but best practice is to check if the delegate actually implements the method you expect it to before calling it, like so:
if ([self.delegate respondsToSelector:#selector(selectedCell:)]) {
[self.delegate selectedCell:cellTitle];
}

TouchJSON How to make a table populated with json clickable?

I am a total newbie on iOS development. After numerous tries; with lots of sample codes I managed to parse a json string from my server and able to display the results in a dynamic tableview. My problem is I cannot make the cells clickable so they would pass the id and the label to another view where another json parse will be performed to display the details of the row.
Below is my code:
#import "jsonviewcontroller.h"
#import "CJSONDeserializer.h"
#import "Otel_ItemViewController.h"
#implementation jsonviewcontroller
#synthesize tableview;
#synthesize rows;
- (void)dealloc {
[rows release];
[tableview release];
[super dealloc];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rows count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
NSDictionary *dict = [rows objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:#"C_NAME"];
cell.detailTextLabel.text = [dict objectForKey:#"CAT_ID"];
return cell;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"http://zskript.net/categories.php"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] retain];
if (dict)
{
rows = [dict objectForKey:#"users"];
}
NSLog(#"Array: %#",rows);
[jsonreturn release];
}
// Do some customisation of our new view when a table item has been selected
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure we're referring to the correct segue
if ([[segue identifier] isEqualToString:#"ShowSelectedMovie"]) {
// Get reference to the destination view controller
Otel_ItemViewController *vc = [segue destinationViewController];
// get the selected index
NSInteger selectedIndex = [[self.tableview indexPathForSelectedRow] row];
// Pass the name and index of our film
[vc setSelectedItem:[NSString stringWithFormat:#"%#", [rows objectAtIndex:selectedIndex]]];
[vc setSelectedIndex:selectedIndex];
}
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#end
And below is the view that will display the detail:
#import "Otel_ItemViewController.h"
#implementation Otel_ItemViewController
#synthesize selectedIndex, selectedItem;
- (void)viewDidLoad
{
[super viewDidLoad];
[outputLabel setText:selectedItem];
[outputText setText:selectedItem];
[outputImage setImage:[UIImage imageNamed:[NSString stringWithFormat:#"%d.jpg", selectedIndex]]];
}
#end
Currently, when I click the cells in the table, Although I have set it to push to the next view, nothing happens. Would someone please advise?
Here is the updated code.
My root view controller:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict = [rows objectAtIndex: indexPath.row];
DetailViewController *controller = [[DetailViewController alloc] init];
controller.CATNAME = [dict objectForKey:#"C_NAME"];
controller.CATNUMBER = [dict objectForKey:#"CAT_ID"];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
And here is DetailViewController.h:
#interface DetailViewController : UIViewController {
NSString *CATNAME;
NSInteger CATNUMBER;
IBOutlet UILabel *labelId;
IBOutlet UILabel *LabelName;
}
#property (nonatomic) NSInteger CATNUMBER;
#property (nonatomic, retain) NSString *CATNAME;
#end
And DetailViewController.m:
#import "DetailViewController.h"
#implementation DetailViewController
#synthesize CATNAME, CATNUMBER;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void) viewDidLoad
{
LabelName.Text = CATNAME;
labelId = CATNUMBER;
// [LabelName setText:CATNAME];
// [labelId setText:CATNUMBER];
}
You have to implement this method
EDIT: Loading a new view
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict = [rows objectAtIndex: indexPath.row];
MyNewViewController *controller = [[MyNewViewController alloc] init];
controller.C_NAME = [dict objectForKey:#"C_NAME"];
controller.CAT_ID = [dict objectForKey:#"CAT_ID"];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
}
In the code above I assume you are using a navigation controller (which is the easiest way to do what you want to be doing). Also I am assuming you have a class that inherits from UIViewController that you want to have displayed. I am also assuming that this class which I called MyNewViewController in my example has two members and properties called C_NAME and CAT_ID respectively.
- (void) viewDidLoad
{
labelName.Text = C_NAME;
labelId = CAT_ID
}
The above my be incorrect as I am doing it out of memory. But the principal stays the same, if you passed the variables correctly it should work, you can have a look at my blog it still needs some work done on it, but it has a nice beginners post and shows how to edit the text of the label. In the code above I am assuming your view contains two labels labelName and labelId respectfully.
In there you have access to what cell was selected and you can then define what needs to happen.

UITableView with JSON help

I am trying to feed in some JSON data to my iPhone app, the data is coming in fine as I have NSLog's telling me so.
The problem I am having is trying to get the results to show in a UITableView. I have a navigation controller underneath a tab bar controller, the navigation controller contains a table view controller which loads another NIB file with a table view connected to a class which is the delegate and data source delegate.
I also need to categorize the results into sections - these being
England
Scotland
Wales
N.Ireland
To get an idea of what JSON string I am using see this one.
As you can see the JSON does not cater for the sections but I am yet to implement this, so i would need to know beforehand so I do not have to amend much code later on.
OK - I am using Stig JSON parser.
Here is my ListVenuesView.h (connected to table view)
#import <UIKit/UIKit.h>
#import "SBJson.h"
#interface ListVenuesView : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *venueList;
NSMutableDictionary *jsonArray;
}
#property (nonatomic, retain) IBOutlet UITableView *venueList;
#property (nonatomic, retain) NSMutableDictionary *jsonArray;
#end
jsonArray is used to store the JSON data and eventually the proper array.
And here is my ListVenuesView.m (key areas in question)
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"Table View Loaded");
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// This is where we load the JSON data
NSURL *jsonURL = [NSURL URLWithString:#"http://www.thebigfishexperience.org.uk/sources/ajax/venue-json.php?location=peterborough"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
NSLog(#"%#", jsonData);
// Convert jsonData to array
self.jsonArray = [jsonData JSONValue];
NSLog(#"%#", jsonArray);
NSLog(#"count is: %i", [self.jsonArray count]);
// Release NSString and NSURL
[jsonURL release];
[jsonData release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.jsonArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSMutableDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Arial" size:15.0];
cell.textLabel.text = [dict objectForKey:#"venueName"];
cell.detailTextLabel.text = [dict objectForKey:#"venueCordDist"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
// Configure the cell...
return cell;
Also how can I use the data in the cells to go to another subview of the nav controller which gives me a back button and displays the info from the JSON string just for that particular cell that has been tapped.
I think this has something to do with it? Not sure though as this is my first app i am building! So probably expect more pleas of assistance - ha ! ;)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"Nib name" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
On selecting a row, as mentioned by u, we are navigating to another view. Let us assume that the view controller is DetailViewController which is a sub-class of UIViewController.
In the DetailViewController.h , declare a NSDictionary object.
In DetailViewController.m, add
-(void)setVenueDict:(NSDictionary*)venueDict
{
if( _venueDict )
{
[_venueDict release];
}
_venueDict = [venueDict retain];
}
In ParentViewController, ur didSelectRow.. method should be like this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"Nib name" bundle:nil];
// ...
// Pass the selected object to the new view controller.
NSDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
[detailViewController setVenueDict:dict];
detailViewController.title = [dict objectForKey:#"venueName"];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
In the second view controller, u can do whatever u want with the _venueDict.
Nathan,
since you want to reuse the data parsed from the JSON feed over more than one ViewController the best way to approach this is to build an object Model so that you can pass the object for the selected row in the list to the detail ViewController.
I would also separate the JSON parsing code into a separate class and not keep it in the ViewController.
You can find classes to fetch JSON on this link.
The result from the custom code to parse the JSON feed would give back a NSDictionary with as keys the section names you mention. And the value in the NSDictionary for those keys would be an array of your custom objects that contain all the relevant data for one row (and detail screen).
Hope this helps you on your way.
jsonArray is NSMutableDictionary.
have to use
[jsonArray objectForKey:key];
//check this line
NSMutableDictionary *dict = [self.jsonArray objectAtIndex: indexPath.row];
this may help.

Table View not populating

I know this is an oft-asked question/problem. I've looked through a bunch of Q&A for my problem, but I guess I'm a little thick, because I didn't see an answer anywhere.
I have a file with in an array that I would like to use to populate a tableView.
The problem is that it's not being called. Neither is numberOfRowsInSection or numberOfSectionsInTableView. I far as I can see, only viewDidLoad was called.
I have 1 section, the number of elements in my array equals 3 (as opposed to nil).
Relevant code is here...
- (void)viewDidLoad {
[super viewDidLoad];
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
NSLog(#"%i \n %#", [matArray count], matArray); // matArray is filled.
NSLog(#"ViewDidLoad"); }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#"CellForRowAtIndexPath");
NSString *text = [matArray objectAtIndex:[indexPath row]];
[[cell textLabel] setText:text];
return cell; }
#interface MaterialTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *materialTableView;
NSArray *matArray;
}
#property (nonatomic, retain) NSArray *matArray;
#end
The other methods are standard.
I guess my problem lies in that I don't completely understand the flow well enough.
Any help would be greatly appreciated. Thanks in advance.
Have you set your UIViewController subclass to be the delegate and dataSource of the UITableView in question? Without doing so, none of the methods you mention will be called.
I suppose you are using a UITableViewController.
If you are using UITableView it is a little bit more complicated (in this case you need to implement UITableViewDelegate, UITableViewDataSource protocols).
[update] This is not your case, you are using UITableViewController.
Add this line to the end of your viewDidLoad method:
[self.tableView reloadData];
Or move this:
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
to the init method. Your init method should look like this:
- (id)initWithStyle:(UITableViewStyle)style {
if ((self = [super initWithStyle:style])) {
FileControl *fileArray = [[FileControl alloc] init];
matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
[fileArray release];
NSLog(#"%i \n %#", [matArray count], matArray); // matArray is filled.
NSLog(#"ViewDidLoad");
}
return self;
}
If you do not see any message in the log, it means that you are not using that method to initialize your object.
Please show all your code in the .m and .h files.
I have a suggestion. Just give a shot for a test. In the - (void)viewDidLoad declare this.
instead of : matArray = [fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]];
Use this: matArray = [[NSArray alloc] initWithArray:[fileArray findUniqueItemsInArray:0 :[fileArray setFileToArray]]];
Did you use
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.matArray count];
}
make sure you have added your tableview delegate to your .h file as shown below.
#interface YourViewController : UIViewController <UITableViewDelegate> {
}
Also make sure that you have connected your datasource and delegate in interface builder.
Do this by doing:
double click on your .xib file so it opens in interface builder.
left click on your tableview just once so its highlighted blue
right click on your tableview now and a menu should pop up.
drag the datasource & delegate to the files owner box.
make sure to save changes while in interface builder.
This should "connect" all the pieces needed to get it to work.
Happy Coding!!

How to push view depending on the row selection?

/*****UPDATED** ***/r.com/YH3cm.png
I am trying to figure out in the above image, how will we know if the user has selected Date or Track.
/UPDATED/
The data I am receving is through a select query and I create an array to store the list. It is dynamic and not necessary limited to two fields, it can have 10 fields also. How will I know which row is selected and how will I push the data on to the next view.
Like in didSelectRowAtIndexPath, how should I push the date or track field on the next view?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (dvController == nil)
dvController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:nil];
Teat *obj = [appDelegate.coffeeArray objectAtIndex:indexPath.row];
dvController.obj = obj;
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:dvController animated:YES];
}
It's still not very clear what you're trying to do. If you want to push a certain view controller depending on what the content of the cell is, but there is no definite arrangement of the rows, I would use the row index to access the array that is the source of your data. Some very loose code:
WhateverObject* selectedObject= (WhateverObject*)[tableDataSourceArray objectAtIndex:indexPath.row];
if( [selectedObject hasAnAttributeYouCareAbout] )
{
MyViewController* theCorrectController= whicheverViewControllerYouWant;
theCorrectController.anAttribute= aValue;
[self.navigationController pushViewController:theCorrectController animated:YES];
}
And here's how you can define your UIViewController subclass MyViewController with specific attributes. In the .h file:
#interface MyViewController : UIViewController {
int anAttribute;
}
#property int anAttribute
#end
In the .m file:
#implementation MyViewController
#synthesize anAttribute;
#end
You can have as many attributes as you want of whatever type, and then you can set them with aViewController.anAttribute as above.
Create objects - dateInfoViewController and trackInfoViewController and then...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
if (row==0)
{
if (self.dateInfoViewController == nil)
{
DateInfoViewController *temp = [[DateInfoViewController alloc] init];
self.dateInfoViewController = temp;
[temp release];
}
else {
dateInfoViewController.title= [ NSString stringWithFormat:#"%#", [sessionInfoDetailsArray objectAtIndex:row]];
YourAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
[delegate.sessionNavigationController pushViewController:dateInfoViewController animated:YES];
}
}
if (row==1)
{
if (self.vetInfoViewController == nil)
{
TrackInfoViewController *temp = [[TrackInfoViewController alloc] init];
self.trackInfoViewController = temp;
[temp release];
}
else {
trackInfoViewController.title= [ NSString stringWithFormat:#"%#", [sessionInfoDetailsArray objectAtIndex:row]];
YourAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
[delegate.sessionNavigationController pushViewController:trackInfoViewController animated:YES];
}
}
I fear it's not perfectly clear what do you want to do... if you need to push a different view depending on the selected row you may simply do something like
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0)
//push view 1
else
//push view 2
}
UPDATE: calling indexPath.row you get the index of the selected row. I guess is up to you to decide what to do depending on what row is selected. To pass this information to the next view you may simply think of a #property field to set, a method to call or a custom init method for the view controller you are pushing. What is the problem with the code you posted?