NSIndexPath associated with UITableView - iphone

I have a table view on my master view, and a textField on my detail view. The app is simple. Add a table view cell with some info. Then if you press the cell, it pushes the detail view and shows the cell's title/text in the text field. In the master view, im using an NSFetchedResultsController. And in the second view, im trying to load the data, but for some reason i am not using my own indexPath variable correctly, because every cell that gets pressed shows the first cells text on the detail view. Code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Set up the cell...
[self configureCell:cell atIndexPath:indexPath];
self.path = indexPath;
//I have tried this as well.
//self.path = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
return cell;
}
Detail View:
-(void)viewWillAppear:(BOOL)animated
{
if (self.context == nil)
{
self.context = [(FBCDAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"FailedBankInfo" inManagedObjectContext:self.context];
[request setEntity:entity];
NSError *error;
NSMutableArray *array = [[self.context executeFetchRequest:request error:&error] mutableCopy];
[self setTableArray:array];
FailedBankInfo *infoData = [self.tableArray objectAtIndex:self.root.path.row];
NSString *string = [NSString stringWithFormat:#"%#", infoData.name];
self.nameField.text = string;
string = [NSString stringWithFormat:#"%#", infoData.city];
self.cityField.text = string;
string = [NSString stringWithFormat:#"%#", infoData.state];
self.stateField.text = string;
[super viewWillAppear:YES];
}

Why not just pass the index path into the detail view controller in the
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
method, with a custom initializer:
- (id)initDetailViewControllerWithIndexPath:(NSIndexPath*)indexPath
?
I'm not familiar with a "root" property on a UIViewController, what is that? It seems to be an attempt to reference the first view controller from the detail view controller. Have you checked to see what self.root.path.row is returning?
Anyway the path property of your first view controller is independent of what ever cell is selected the way you have your code. It is simply set to the indexPath of the last cell that is loaded. If you did want to some how access this property from your detail view controller, it would have to be set in the didSelectRowAtIndexPath method, not the cellForRowAtIndexPath method to be accurate.
I think that if you set the path in didSelectRowAtIndexPath your way should work. But to write the custom initializer, add a property to your detail view controller called path, and then add a custom initializer to the detail view controller like this:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andIndexPath:(NSIndexPath*)indexPath
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.path = indexPath;
}
return self;
}
and call this from the didSelectRowAtIndexPath method of the first view controller using
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:nil bundle:[NSBundle mainBundle] andIndexPath:indexPath];
[self presentViewController:detailViewController animated:YES completion:nil];
(if you're not initializing from a xib, customize which ever initializer that you're using).
Or, instead of passing in the index path, you could pass in an NSDictionary containing the data that you need in the detail view controller (the title and the text).

Related

Insert New UITableViewCell in Master from Detail

I have a simple master-detail application and I'm using the detail view to configure data to insert into the master list.
I have a custom class called "Calculation," which is the object I need to insert into each row.
I can pass the object from the detail view to the master view just fine, it just won't insert a new row.
In the detail view I Initiate my object, populate it with data and send it to the "insertNewObject" method in the MasterViewController using a custom segue:
- (IBAction)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *s = #"1";
NSNumber *n = [f numberFromString:s];
Calculation *calc = [[Calculation alloc] initWithValue:#"$1661.70" descr:#"1 Ounce 24k Gold" textInput:#"1" percentDisplay:#"0%" purityIndex:n metalIndex:n weightUnitIndex:n sliderValue:n];
[segue.destinationViewController insertNewObject:calc];
}
And in the MasterViewController, here is my insert code:
-(void)insertNewObject:(NSObject *)newCalculation {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:newCalculation atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSObject *object = [_objects objectAtIndex:indexPath.row];
cell.textLabel.text = [object valueForKey:#"value"];
cell.detailTextLabel.text = [object valueForKey:#"descr"];
cell.textLabel.shadowColor = [UIColor blackColor];
cell.textLabel.shadowOffset = CGSizeMake(0, -1);
return cell;
}
I can print the object all day with NSLog in the MVC, but not matter how many times I add an object from the detail view controller, the array count is always 1, and no cell ever gets added to the tableview.
The same exact code works fine if I instantiate the object in MVC, and insert it.
A segue is really the wrong mechanism for sending data from detail to master. (It works great the other direction!) You'd be better off defining a delegate protocol that has -(void)insertNewObject:(NSObject *)newCalculation; as a required method, making your master implement that protocol, and passing it as a delegate to your detail controller.
Then the detail controller just calls [delegate insertNewObject:calc];.

Reloading data on side-by-side UITableView

I am trying to create an application that has two UITableViews placed side-by-side. The left one lists article categories and the right one displays article previews (kind of like flipboard's search view).
On the left tableview's didSelectRowAtIndexPath, I am supposed to download the article and display the previews on the right UITableView. However, I cannot seem to make this work.
My assumption is that I reload the data on the tableview before the download is finished. Any suggestions?
EDITED:
Here's my current code:
- (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];
if (tableView.tag == 1)
{
//if it's the left tableView (no problem here)
NSDictionary *catDic = [[Category categories] objectAtIndex:indexPath.row];
cell.textLabel.text = [catDic valueForKey:#"name"];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:[UIFont labelFontSize]];
}
if (tableView.tag == 2)
{
//if it's the right tableView
ArticlePreview *articleView = [[ArticlePreview alloc] initFlexibleHeightRowForArticleInfo:[self.articleInfos objectAtIndex:indexPath.row]];
//ArticlePreview is a custom class that create the articlePreview view,
//articleInfos is a variable that holds the articles in core data
[cell.contentView addSubview:articleView];
[articleView release];
}
}
return cell;
}
-(void) loadArticlePreview: (NSNumber *)_idx
{
[Category downloadArticlesforIndex:[_idx intValue]];
AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"ArticleInfo" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
self.articleInfos = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
[self.articlePreviewTableView reloadData];
//articlePreviewTableView is the right table view identifier, hooked with IBOutlet and all
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView.tag == 1) //if it's the left table
{
[self performSelectorInBackground:#selector(loadArticlePreview:) withObject:[NSNumber numberWithInt:indexPath.row]];
}
}
The problem is that the right tableview does not refresh. I think these methods are where the problem probably is.
According to your code, if you dequeue a UITableViewCell, its going to use the old cell, without any modifications for the actual cell that you need. Change it to so:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}//after this, use the tableView tag to identify.
You are also adding a content view to the preview table cell. I strongly recommend you create a custom UITableViewCell class when you do this. I found that to be the only way the adding subviews works in cells and is a lot easier to manage the cells with the custom class.
I assume you are doing the downloading in some method in the ArticlePreview. You don't need to reload the tableView once the download is finished. Since the ArticlePreview object has been added as the cell's subview, when the download is finished in it, call setNeedsDisplay when the view is content is downloaded.
You cannot reload your tableview in a background thread. You will have to create a method like this
-(void)reloadTable
{
[self.articlePreviewTableView reloadData];
}
Then call this method on the main thread inside the -(void) loadArticlePreview: (NSNumber *)_idx method
Hope this solves ur problem.

Inserting data from one table to another table

I have two UITableViewController classes, MainTableController and SubTableController.
From AppDelegate class I am calling MainTableController class.
At first this class is empty, and there is button named "show list" in this class.
When I click on this button I will go to SubTableController and there I have a list of actions in form of table.
Now if I choose to first cell action then that action name has to come on my first cell of table in MainTableController. But I am not able to print that name in table of MainTableController class.
In SubTableController:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ActionList * actionListObj = [appDelegate.actionArray objectAtIndex:indexPath.row];
self.chooseActions = actionListObj.actionName;
MainTableController * mainViewController = [[MainTableController alloc] init];
[mainViewController getAction:self.chooseActions];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
In MainTableController:
-(void) viewWillAppear:(BOOL)animated{
[self reloadData];
}
-(void) reloadData{
[self.myTableView reloadData];
}
-(void) getAction: (NSString *) actionChoose{
self.action = actionChoose;
[self reloadData];
}
-(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];
}
// Configure the cell...
cell.textLabel.text = self.action;
return cell;
}
When I debug, in MainTableController I am getting the action in getAction method but in table cell text string is null.
Can anyone please help me regarding this?Where am I going wrong?
You are allocating and initializing a new view controller each time you select a cell in SubTableController.
MainTableController * mainViewController = [[MainTableController alloc] init];
and of course, it isn't the one in place in the navigation stack.
You need to make these two controllers communicate.
I suggest that the sub view controller define a property on the main one, in order to message it when needed.
In SubTableController, add a property and synthesize it :
#property(readwrite, assign) MainViewController *mainViewController;
// and ...
#synthesize mainViewController;
Of course when you push the sub view controller, don't forget to set the property.
// in main view controller
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// alloc/init the sub VC
subVCInstance.mainViewController = self;
[self pushViewController:subVCInstance ......
Now when a row is selected in the sub one, message the main one, without alloc/init a new MainViewController object :
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ActionList * actionListObj = [appDelegate.actionArray objectAtIndex:indexPath.row];
self.chooseActions = actionListObj.actionName;
//MainTableController * mainViewController = [[MainTableController alloc] init];
[self.mainViewController getAction:self.chooseActions];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
This should work just fine.
In didSelectRowAtIndexPath of the SubTableController class, you are allocating new MainTableController to send the data.
MainTableController * mainViewController = [[MainTableController alloc] init];
[mainViewController getAction:self.chooseActions];
You should not do like that. Because the existing mainview will be different from the newly allocated one. You should use delegate to give back the data. For more info on Protocols and delegates, see here
More example here

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.

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?