I have a tableview as a parent view controller with a child modal view controller. In the modal view controller, when users tap on a row, I'd like to set the parent's property 'filter.' However, it's just returning null.
How do I pass the NSString filter property back to its parent view? And should I be instantiating a parent view controller in the didSelectRowAtIndexPath method?
UPDATE: Solved using Delegates, followed this tutorial.
Below is the code for the modal view controller:
#import "FilterViewController.h"
#import "ContactsTableViewController.h"
#interface FilterViewController ()
#end
#implementation FilterViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.filterTable.dataSource = self;
self.filterTable.delegate = self;
[self performSelector:#selector(retrieveFilteredEvents)];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.filterEvents count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"filterTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
self.eventTitle = [tempDict objectForKey:#"eventType"];
cell.textLabel.text = self.eventTitle;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
NSString *string = [tempDict objectForKey:#"eventType"];
ContactsTableViewController *contactVC = [[ContactsTableViewController alloc] init];
contactVC.filter = string;
[self dismissViewControllerAnimated:YES completion:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateParent" object:nil];
}
#pragma mark - Helper Methods
- (IBAction)done:(id)sender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)retrieveFilteredEvents
{
PFQuery *retrieveEvents = [PFQuery queryWithClassName:#"eventTypes"];
[retrieveEvents orderByAscending:#"eventOrder"];
[retrieveEvents findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
self.filterEvents = [[NSArray alloc] initWithArray:objects];
}
[self.filterTable reloadData];
}];
}
#end
There are multiple ways to approach this problem. The easiest I think would be setting a property in your parent class that would change every time you update the child.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *tempDict = [self.filterEvents objectAtIndex:indexPath.row];
NSString *string = [tempDict objectForKey:#"eventType"];
self.parentViewController.filter = string;
[self dismissViewControllerAnimated:YES completion:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"updateParent" object:nil];
}
The other option would be to use delegates. This is probably a cleaner solution but is not as beginner friendly.
http://iosdevelopertips.com/objective-c/the-basics-of-protocols-and-delegates.html
What you are doing here:
ContactsTableViewController *contactVC = [[ContactsTableViewController alloc] init];
contactVC.filter = string;
is instantiating a whole new controller that has nothing to do with the actual controller that presented your FilterViewController.
Try using this, instead, which accesses the view controller that presented FilterViewController:
ContactsTableViewController *contactVC = (ContactsTableViewController*)self.presentingController;
contactVC.filter = string;
Hope this helps.
Alloc init gives you a brand new object, NOT a reference to your existing one. There are a couple of ways to get a reference to your table view. I recommend delegation, it's a flexible approach that will continue to work even if you present your view in a different way than modal.
create a protocol
#protocol PassSomeData
-(void)childViewController:(UIViewController *)viewController passedSomeData:(id)data;
#end
create a delegate in the childview controller
#interface ViewControllerThatIsPresentedModally :UIViewController
#property(nonatomic,assign) id<PassSomeData>delegate;
#end
in prepareForSegue of the view controller that is presenting the modal write this
UIViewController *vc = [segue destinationViewController];
if ([vc isKindOfClass:[ViewControllerTahIsPresentedModally class]){
[((ViewControllerThatIsPresentedModally *)vc) setDelegate:self];
}
when your user clicks something that allows some data to be collected
you do
[self.delegate viewController:self passedSomeData:yourData];
and your method in the parent view controller will be called with your data
your presenting view controller needs to conform to the PassedSomeData protocol and implement the given method as well
If it's a simple property set, you could do
[self.parentViewController performSelector:#selector(setSomething:) withObject:...]
or
[self.presentingViewController performSelector:#selector(setSomething:) withObject:...]
Delegates is a much better way, though :-)
Related
I know it's a commom problem but the cellForRowAtIndexPath: is not called when I use [actionTableView reloadData];. I already linked dataSource and delegate thanks to the storyboard but it doesn't solve the issue.
Here's a part of my code:
SearchViewController.h
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate>
#property (strong, nonatomic) IBOutlet UITableView *actionTableView;
#property (strong, nonatomic) IBOutlet UISearchBar *actionSearchBar;
#property (strong, nonatomic) NSMutableArray *actionsArray;
#property (strong, nonatomic) NSMutableArray *filteredActionArray;
#end
SearchViewController.m
#import "SearchViewController.h"
#import "Action.h"
#interface SearchViewController ()
#end
#implementation SearchViewController
#synthesize actionsArray, actionTableView, filteredActionArray, actionSearchBar;
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [filteredActionArray count];
} else {
return [actionsArray 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];
}
NSLog(#"Aloha");
// Create a new Action object
Action *a = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
a = [filteredActionArray objectAtIndex:indexPath.row];
} else {
a = [actionsArray objectAtIndex:indexPath.row];
}
// Configure the cell
cell.textLabel.text = a.nomAction;
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
// Update the filtered array based on the search text and scope.
// Remove all objects from the filtered search array
[self.filteredActionArray removeAllObjects];
// Filter the array using NSPredicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.nomAction contains[c] %#",searchText];
filteredActionArray = [NSMutableArray arrayWithArray:[actionsArray filteredArrayUsingPredicate:predicate]];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
// Tells the table data source to reload when text changes
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
// Tells the table data source to reload when scope bar selection changes
[self filterContentForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
As you see I also use a searchBar to filter the array, but w/o this it doesn't work either.
EDIT: SPECIFICATION OF THE PROBLEM: reloadData works only if I call it within the viewController. Not if I call it from another viewController. Obviously for the two cases I call the same function updatingTableView located in the viewcontroller where the tableView is. Any ideas to reload the tableView from anotherViewController?
SearchViewController.m (works)
-(IBAction)update{
[self updatingTableView:nil];
}
-(void)updatingTableView:(NSData*)someData {
actionsArray = [NSArray arrayWithObjects:#"item1", #"item2", #"item3", nil];
[actionTableView reloadData];
}
AnotherViewController.m (does not work)
-(IBAction)updateFromElsewhere{
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:#"Main"
bundle: nil];
SearchViewController *searchViewController = (SearchViewController*) [mainStoryboard
instantiateViewControllerWithIdentifier: #"searchcontroller_id"];
[searchViewController updatingTableView:nil];
}
NB: I can pass some data from a view controller to the other without problem here.
One thing I always run into when struggle up a table view is connecting the table with the interface using interface builder. But when you call [actionTableView reloadData] without having the connection made to the table, nothing will happen.
I ways forget that super simple step. Hope this helped
The problem is you never initialize actionsArray and filteredActionArray to be non-nil. As a result, numberOfRowsInSection always returns 0, so cellForRowAtIndexPath won't be called.
Finally found the solution!
In SearchViewController.m where the tableView is, put this in viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(updatingTableView) name:#"reload_data" object:nil];
With still:
-(void)updatingTableView{
[actionTableView reloadData];
}
In AnotherViewController.m
[[NSNotificationCenter defaultCenter] postNotificationName:#"reload_data" object:self];
how to reload tableview of another uiviewcontroller in current viewcontroller
Thanks everyone!
I am new to programming and am probably hung up on a simple problem. I am using parse for my array in my tableview. When the row is selected i want to segue to a search bar on another view controller. The segue works fine and the tableview works fine but i can't seem to get the objectId to pass.
#import "bookmarkViewController.h"
#import "Parse/Parse.h"
#import <ParseUI/ParseUI.h>
#import "ViewController.h"
#implementation bookmarkViewController
#synthesize postArray;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self
action:#selector(refreshButtonHandler:)]];
}
- (void)viewWillAppear:(BOOL)animated
{
if ([PFUser currentUser])
[self refreshButtonHandler:nil];
}
#pragma mark - Button handlers
- (void)refreshButtonHandler:(id)sender
{
//Create query for all Post object by the current user
PFQuery *postQuery = [PFQuery queryWithClassName:#"Post"];
[postQuery whereKey:#"author" equalTo:[PFUser currentUser]];
// Run the query
[postQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
//Save results and update the table
postArray = objects;
[self.tableView reloadData];
}
}];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
// Return the number of rows in the section.
return postArray.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];
}
// Configure the cell with the textContent of the Post as the cell's text label
PFObject *post = [postArray objectAtIndex:indexPath.row];
[cell.textLabel setText:[post objectForKey:#"textContent"]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath{
NSLog(#"cell tapped");
PFObject *post = [postArray objectAtIndex:indexPath.row];
NSLog(#"%#", post.objectId);
[self performSegueWithIdentifier:#"searchBookmark" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
ViewController *vc = [segue destinationViewController];
vc.labelText = post.objectId;
}
}
#end
at vc.label.text i always get use of undeclared identifier "post" but i can't seem to figure out how to get it recognized. It is in the above method.
the NSLogs reply correctly 16:17:27.513 [App] cell tapped
[App] cgdVY7Eu9h
Change your didSelectRowAtIndexPath and prepareForSegue to this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath* )indexPath{
[self performSegueWithIdentifier:#"searchBookmark" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSLog(#"cell tapped");
PFObject *post = [postArray objectAtIndex:indexPath.row];
NSLog(#"%#", post.objectId);
ViewController *vc = [segue destinationViewController];
vc.labelText = post.objectId;
}
}
Post is a local variable that you created inside didSelectRowAtIndexPath, so it can't be used outside that method. The easy way to fix this, is to pass post as the sender argument in performSegueWithIdentifier:sender:. You can pass any object you want as the sender.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSLog(#"cell tapped");
PFObject *post = [postArray objectAtIndex:indexPath.row];
NSLog(#"%#", post.objectId);
[self performSegueWithIdentifier:#"searchBookmark" sender:post];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
PFObject *post = (PFObject *)sender;
ViewController *vc = [segue destinationViewController];
vc.labelText = post.objectId;
}
UIViewController -> segue -> UITableViewController
I had one problem that i solved with answer -1- Thanks.
So i had a kind of UIViewController and i wanted with button just segue to another UITableViewController and i noticed that it stacked and was frozen. I could not scroll my Table ...
My Code was :
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
MasterViewController *controller =segue.destinationViewController;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentViewController:controller animated:YES completion:nil];
}
My CPU was over 100% overloaded.
So the answer number 1 worked for me well. New Code is then :
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
MasterViewController *vc = [segue destinationViewController];
}
and the table with 30 entries works now just like a charm =)
Right now I have a kind of pop-up selector so that the user can pick an option on my screen. Please see this sample project to see what I mean.
I'm using the same method as this sample, except that I have three different buttons where the user will select. My problem is that I am using this code:
- (void)itemSelectedatRow:(NSInteger)row
{
NSLog(#"row %lu selected", (unsigned long)row);
[self.selectSeverity setTitle:[self.severityArray objectAtIndex:row] forState:UIControlStateNormal];
[self.selectStatus setTitle:[self.statusArray objectAtIndex:row] forState:UIControlStateNormal];
[self.selectGender setTitle:[self.genderArray objectAtIndex:row] forState:UIControlStateNormal];
}
...and it is changing the name of the button for all three every time the user selects one. So for example, if the user taps the "selectSeverity" button, and chooses the item on row three, the name for the selectStatus and selectGender button will also change to the item on row three on its own corresponding array.
What I need to do is somehow separate this method so the button's title changes only when a row has been selected in its own array: how can I do this?
More information:
I have these tableViews embedded in a Navigation Controller:
statusViewController.m/.h
genderViewController.m/.h
pickerViewController.m/.h (this corresponds to the Severity button)
Each have a delegate with a separate ID, but the same content:
#protocol correspondingViewControllerDelegateHere <NSObject>
#required
- (void)itemSelectedatRow:(NSInteger)row;
#end
#interface correspondingViewControllerHere : UITableViewController
#property (strong, nonatomic) NSArray *correspondingArrayHere;
#property (assign, nonatomic) id<statusViewControllerDelegate> delegateIdHere;
#end
Each have the same content in the .m file as well, but correspond to their own delegates, arrays, etc.
#implementation statusViewController
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.statusData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"CellIdentifierHere";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [self.statusData objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if ([self.delegateIdHere respondsToSelector:#selector(itemSelectedatRow:)]) {
[self.delegateIdHere itemSelectedatRow:indexPath.row];
[self dismissViewControllerAnimated:YES completion:nil];
}
}
#end
In manualViewController.h (this is the view where they are implemented) I have declared the delegates.
Lastly, in the file manualViewController.m, I have the following code to implement them:
- (IBAction)showinfo:(id)sender
{
UINavigationController *navigationController = (UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:#"pickerVC"];
pickerViewController *tableViewController = (pickerViewController *)[[navigationController viewControllers] objectAtIndex:0];
tableViewController.severityData = self.severityArray;
tableViewController.navigationItem.title = #"Triage Severity Levels";
tableViewController.delegate1 = self;
[self presentViewController:navigationController animated:YES completion:nil];
}
- (IBAction)showStatus:(id)sender {
UINavigationController *navigationController = (UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:#"statusVC"];
statusViewController *tableViewController = (statusViewController *)[[navigationController viewControllers] objectAtIndex:0];
tableViewController.statusData = self.statusArray;
tableViewController.navigationItem.title = #"Triage Severity Levels";
tableViewController.delegate3 = self;
[self presentViewController:navigationController animated:YES completion:nil];
}
- (IBAction)showGender:(id)sender {
UINavigationController *navigationController = (UINavigationController *)[self.storyboard instantiateViewControllerWithIdentifier:#"genderVC"];
genderViewController *tableViewController = (genderViewController * [[navigationController viewControllers] objectAtIndex:0];
tableViewController.genderData = self.genderArray;
tableViewController.navigationItem.title = #"Triage Severity Levels";
tableViewController.delegate2 = self;
[self presentViewController:navigationController animated:YES completion:nil];
}
SO as I said before, I think the code lies in the itemSelectedAtRow. Can someone help me separate this method so that the choice of one item does not affect the choice of another item?
Thanks
One solution is to change the protocol to require three different methods
#protocol correspondingViewControllerDelegateHere <NSObject>
#required
- (void)itemSelectedSeverityAtRow:(NSInteger)row;
- (void)itemSelectedStatusAtRow:(NSInteger)row;
- (void)itemSelectedGenderAtRow:(NSInteger)row;
#end
Then implement the three methods in the manualViewController and call the appropriate method from each of the other view controllers.
I am trying to go from a UITableView with prototype cells to a detailviewcontroller of the item I selected on.
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"historyToDetail"])
{
BYFHistoryDetailViewController *controller = (BYFHistoryDetailViewController *)segue.destinationViewController;
controller.workOut = [[BYFWorkOut alloc] init];
controller.workOut=_selectRow;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BYFHistoryTableViewController *detailViewController =[[BYFHistoryTableViewController alloc] init];
NSArray *items = [[BYFworkOutStore sharedStore] allItems];
BYFWorkOut *selectedItem = items[indexPath.row];
_selectRow = selectedItem;
}
What is not happening is the transition from the table to detail I have a push segue from the prototype cell to the details.
What am I missing?
You are doing quite a lot wrong here. When using segue's you don't create an instance of the class. You simply call:
[self performSegueWithIdentifier:#"MySegue" sender:self];
This will use the segue you have defined in the storyboard. Where MySegue is the segue ID you created.
When you want to pass in data you use the callback
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
BYFHistoryDetailViewController *vc = (BYFHistoryDetailViewController *)[segue destinationViewController];
vc.workOut = selectedItem;
}
But using this callback will mean you will need to store selectedItem somewhere after you click the row so you can access it here.
EDIT
Your code seems a bit odd here also.
You set workout to a new object.
detailViewController.workOut = [[BYFWorkOut alloc]init];
Create another object from data.
NSArray *items = [[BYFworkOutStore sharedStore] allItems];
BYFWorkOut *selectedItem = items[indexPath.row];
And then assign the new object, overwriting the previous one.
//give detail view controller a pointer to the item object in row
detailViewController.workOut = selectedItem;
There is no need to have the first line of code at all
EDIT 2
If you only going to be using the one selected item at a time. you can do this in your UITableViewController class.
#implementation MyTableViewControllerClass
{
BYFWorkOut *_selectedItem;
}
inside didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *items = [[BYFworkOutStore sharedStore] allItems];
_selectedItem = items[indexPath.row];
}
EDIT 3
I've modified the code you posted here. You didn't add the first line of code i posted. Please look at this:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"historyToDetail"])
{
BYFHistoryDetailViewController *controller = (BYFHistoryDetailViewController *)segue.destinationViewController;
controller.workOut = _selectRow;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *items = [[BYFworkOutStore sharedStore] allItems];
_selectRow = items[indexPath.row];
[self performSegueWithIdentifier:#"historyToDetail" sender:self];
}
You need to name your segue and call the method:
[self performSegueWithIdentifier:#"MySegue" sender:self];
I have a UITableView which has different types of files and folders in it, Right i have set a method that passes to another view controller once clicked on a row. What i need is that once a row is clicked on it checks what kind of a file is in the row and then connects to different uiviewcontrollers on the basis of that.
My UiTableView has two items in each cell
A Cell Label & Cell Detail Text Label
The DetailTextLabel holds the Subject type
i.e. Folder (For Folders) & File (For Files like jpeg. , png., etc.)
I want to use the if condition in the didselectrowatindexpath to distinguish between file and folder
You can do that by checking value of cell.detailTextLabel.text like following:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *str = cell.detailTextLabel.text;
if ([str isEqualToString:#"Folder"])
{
// Open Folder Detail View. For Example:
FolderViewController* objVC = [[FolderViewController alloc] initWithNibName:#"FolderViewController" bundle:nil];
[self.navigationController pushViewController:objVC animated:YES];
}
else if ([str isEqualToString:#"File"])
{
// Open File Detail View. For Example:
FileViewController* objVC = [[FileViewController alloc] initWithNibName:#"FileViewController" bundle:nil];
[self.navigationController pushViewController:objVC animated:YES];
}
}
in .h file
#import "FolderViewController.h"
#import "FileViewController.h"
#interface mainViewController : UIViewController {
FolderViewController *folderViewObj;
FileViewController *fileViewObj;
}
in .m file
- (void)viewDidLoad {
[super viewDidLoad];
folderViewObj = [[FolderViewController alloc] initWithNibName:#"FolderViewController" bundle:nil];
fileViewObj = [[FileViewController alloc] initWithNibName:#"FileViewController" bundle:nil];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tblObj cellForRowAtIndexPath:indexPath];
NSString *lblText = cell.DetailTextLabel.text;
if ([lblText isEqualToString:#"Folder"]) {
[self.navigationController pushViewController:folderViewObj animated:YES];
}
else if ([lblText isEqualToString:#"File"])
{
[self.navigationController pushViewController:fileViewObj animated:YES];
}
}
-(void) dealloc {
[folderViewObj release];
[fileViewObj release];
[super dealloc];
}
using this way, object of FolderViewController and FileViewController is created only once not all time when user can select the row of uitableview.