which method will be called when i switch between tabs in tabBarController? - ios

which method will be called when i switch between tabs in tabBarController
i know at first time it will call viewDidLoad method ,i want to know is there any method that come in action when i switch to a particular tab (second time or third time ) .
regards

You can use the UITabBarControllerDelegate method tabBarController:didSelectViewController::
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
//do something
}

The method viewWillDisappear: is triggered each time you are about to leave the current view controller (and hence the current tab) and viewWillAppear: is triggered each time a view is about to be displayed.
A full reference for these methods can be found in the UIViewController docs.

This is pretty old, but it does come up on Google and is linked to from another answer. So, I thought I'd update it.
If your UITableBarController is displaying a UIViewController (i.e. its view) then you have to check the ViewController methods that fire when a view disappears and appears. You could use viewWillDisappear to find out if your view is about to be switched away from, and viewWillAppear to test if your view just got switched back to. Notice, the TabBarController typically keeps the ViewControllers loaded, just their views are moved out and in. The problem with using the TabBarDelegate method is that you need to know the name of your viewController, which makes that a dependency. Change the name and it will probably break with xcode's poor ability to rename Class String representations. Avoid it. Besides you don't want a bunch of conditional junk checking to see if your tabbar just loaded a particular tab unless you cannot avoid it. The other thing to notice is that if a particular tab presents a TableViewController you may have to resort to other techniques if you need data in the cells to change in response to being switched away from. I'm using willMoveToWindow:(UIWindow *)newWindow to get notified in the UITableViewCell case when the view goes away. There's probably a better way.

Related

Switching between UIViewControllers in story board

As someone who usually used separate xibs in the past I thought I'd give storyboard a go as it seemed a lot simpler to use and much easier to develop with. I've been writing an application where the essential set up is this:
At the top of all this is a UINavigationController (first level). Then I have Multiple UIViewControllers (second level) with buttons in them which you can tap to switch between the second level UIViewControllers.
However a problem occurs when I start switching between the second level UIViewControllers. I first thought this was an initialisation problem with the NSMutableArrays because in my code I have a NSTimer set to loop periodically and found when I set a breakpoint during it, when I went forward to the next timer tick event there appeared to be different instances of the same NSMutableArrays and it seemed a gamble to try and insert new values into these array with it sometimes working, sometimes not (as it may or may not insert into the correct instance).
Then, looking at the memory usage under Debug Navigator I found the issue. Each time I "switched" between the UIViewControllers a new UIViewController was being initiated, along with all new variables.
The code I am using to switch between them is
-(void) perform {
[[[self sourceViewController] navigationController] pushViewController:[self destinationViewController] animated:NO];
}
Or essentially a push segue transition. This also explains why when I tried to switch back to my view, the data on that view was lost as it is a complete new view.
Does anyone know how to switch between multiple ones of these UIViewControllers (say 5) essentially like a UITabViewController would except without the tab bar being present?
First option you can do this: You can use a tabbarcontroller for switching viewcontroller and hidden the tabbar. Then on buttonclick setthe tabbar index.
Second option you can do this: Create one more view controller and in this viewcontroller subview the all switching viewController and when you want to switch viewcontroller just bring that viewcontroller view to front by delegate.
Do you need the navigation bar and other features provided by your top level navigation controller?
If not, you could use a UIPageViewController instead.
You set up all your second level view controllers and then just have to tell the page view controller which one to display.
If you implement the associated delegate methods, it will automatically provide swipe gestures to switch between them and nice animations to get them on and off screen.
You can also get it to put a UIPageControl at the bottom showing a dot for each VC with the dot for the current VC highlighted.

Return values to presenting view controller when navigation back button pressed

I'm having trouble piecing this all together. I have a view controller that opens up another (pushes it on to the navigation stack). On that presented view controller, the user enters a value in a text view. When the user pushes the back button in the navigation, I want to be able to pass the value that they entered in the text view back to the presenting controller.
I've looked for a way to use unwind segue with the back button but haven't found anything. When I create my back button (programmatically) I use initWithTitle:style:target:action but I'm not sure how in implementing the action method that I'll be able to access the value set in the presented controller. Might have to use a delegate to link the two, but not sure of the exact integration point for this scenario.
I feel like I'm so close here and a little help would get me there. Thanks!
The two most common models to use for this interaction are for the child view controller to have either a delegate or a completion block. Either would be set in the prepareForSegue method. My personal preference is the completion block method just because it keeps code contained, but ymmv.
There are also multiple models for detecting when your child view controller is dismissed and you need to invoke the delegate and/or completion:
Use a custom back button. Not a fan of this as it can be an issue to create a back button that really looks and acts like the Apple original, especially if supporting iOS 6 and iOS 7.
Hook viewDidDisappear and see if you're still in the navigation controller's viewControllers array. This is better as the back button works right, but it still feels kind of hokey.
Use the UINavigationBarDelegate method navigationBar:shouldPopItem: This is attractive, especially if you have other validation that needs to happen like checking for saved/unsaved values. To implement this you'll have to subclass UINavigationController and forward the method to your child view controller.
EDIT: Details on Option 2:
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
if(![self.navigationController.viewControllers containsObject:self])
{
// We're not still in the navigation stack so we must've been
// popped. If we were pushed, viewDidDisappear would be called
// but viewControllers containsObject:self would be true
}
}
EDIT: Clarified Option 3: in your navigation controller subclass
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
UIViewController* top = self.topViewController;
if([top respondsToSelector:#selector(navigationBar:shouldPopItem:)])
return [(id)top navigationBar:navigationBar shouldPopItem:item];
return [super navigationBar:navigationBar shouldPopItem:item];
}
Then you can implement navigationBar:shouldPopItem: in the classes that need the functionality.
the back button does not actually comes up with any event associated with itself so that you can pass the values between the previous and to be Popped ViewController.
You would have to implement Delegate pattern to pass values. In this case as you cant catch when backButton is pressed, you need to use custom leftBarButtonItem or use a image with < in itself.

ViewController loses its properties when I go back

I have two ViewControllers. The first has UITableview that I push data from to the second ViewController. Whenever I go back, the first ViewController loses its properties - Its navigationbar background disappears and for example the sidebar menu does not work either. Is there any way I could reload it while pushing the back button?
Thank you
Sounds like you are probably doing your setup in viewWillAppear instead of viewWillLoad. This means that when the view will appear on return, the setup is happening again and perhaps leaving you in an unexpected state. Put breakpoints in your view controller delegate methods and see what order things are being called in and why.

Specifying a Delegate before ViewDidLoad in Tabs

So, I followed this tutorial: http://enroyed.com/ios/how-to-pass-data-between-ios-tab-bars-using-delegate/
And the most important part of the tutorial:
- (void)viewDidLoad
{
[super viewDidLoad];
SecondViewController *svc = [self.tabBarController.viewControllers objectAtIndex:1];
svc.delegate = self; //important !! otherwise delegation will not work !
}
The problem is that even if I put it in "viewWillLoad", it still forces me to click on my tab before it initializes. How can I specify this before I click on the tab?
Edit
I have a three tab project. I used that tutorial in the link pass data from tab 1 to tab 2. The data passed is a url from a webview on tab 1 to a url on tab 2. The url gets pass when I click a link on the 1st tab.
The data does get passed, but only if I physically click on the 2nd tab first and then click back to the 1st and click on the link.
So, it appears to me that my code above only runs if I physically click on the 2nd tab.
Your problem is that - until you actually go to tab item 2, secondViewController is not fully initialised, and so there is no data to transfer from vc2 to vc1. In particular, secondViewController's view has not yet loaded, so there is no value to be had from it's slider yet, and no slider, so also no IBAction method to call to trigger the delegate method. Indeed, as the data transfer is only triggered on moving the slider in VC2, it should be fairly obvious that until you go to vc2 and move the slider, nothing is going to happen.
The example you link to uses the delegation pattern, which seems a fairly poor way to deal with your problem. The delegation pattern most comfortably fits with the scenario where there is a hierarchical relationship between delegator (owned) and delegatee (owner) ... not always, but most commonly. In a tab bar controller, the relationships are more like kindred child relationships to the tab bar controller itself.
You haven't offered enough detail in your question as to what you want to achieve, but you need to consider this:
When a tabBarController loads, all of it's child viewControllers are initialised but their views are not loaded.
This means that these methods do get called:
//if loading from a xib or in code
- (id) initWithNibName:bundle
//if loading from a storyboard
- (id) initWithCoder:
- (void) awakeFromNib
But the view loading methods (viewDidLoad, viewWillAppear etc) do not get called as the view does not get loaded unless you actually open the relevant tab.
You could solve this by putting an initialised variable into your viewController2 (in one of the init methods) and accessing that variable via property syntax from vc1. But then, you might as well just put an initialised value directly into vc1. You need to think closely about how each vc is dependent on the other, how you can decouple that dependency, and perhaps how to set up an independent data source that both vcs can access as needed. This could be a model class, or NSUserDefaults, or a property in your appDelegate... just a few of the many possible solutions.

Pop to root view controller without animation crash for the table view

I have 3 view controller in a tab bar controller. Clicking on any tab loads its root view controller in the navigation stack.
e.g. tab1, tab2, and tab3.
The 2nd view controller in the navigation stack (tab2VC2), has a tableView.
Click on tab2 show VC in tab2, then tap on tab1, tries to go to its rootVC. Then the app is crashing saying
[UserDetailVC
tableView:cellForRowAtIndexPath:]:
message sent to deallocated instance
0xe0a23b0
If I popToRootVC with animation then its okay. I found viewDidAppear in the tab2VC2 is called where the tableView.reloadData is called, then dealloac, seems in the meantime reloadData starts working, the table is released. in case of animation, it gets some time, so it dont crash. But without animation, it is crashing.
Do you think, its an iPhone bug? or I am doing wrong? Since pop to root controller have an option without animation, it should work, not it?
#pragma mark Tab bar controller delegate
- (void)tabBarController:(UITabBarController *)tbController didSelectViewController:(UIViewController *)viewController {
int i = tbController.selectedIndex;
NSArray *mycontrollers = tbController.viewControllers;
[[mycontrollers objectAtIndex:i] popToRootViewControllerAnimated:NO];
}
I consider this a bug or at least a weakness in UIKit, but I've already blown half my day on it, so I'm not going to write it up with example code and report it to Apple right now. If someone else wants to do that, I would appreciate it.
Here's what I think is going on under the hood. You have a UITableViewController, let's call it myTable, on the stack of a UINavigationController, and that navigation stack is hidden because it's on an unselected tab or whatever. Then, you call [myTable.tableView reloadData], and iOS cleverly optimizes by not reloading the data right away, because the user won't be seeing it anyway if it's on a hidden tab. Instead, the reload request is deferred and stored somewhere for when the view is shown. But before it can be shown, you pop myTable off the navigation stack. When myTable's original tab is shown, the reload request gets executed, but its dataSource is no longer there, so it's a bad access.
Now from my tests with a subclass of UITableViewController that uses the automatically provided tableView property (not loaded from a NIB file), the UITableView is not being deallocated when myTable deallocates as in the situation above. That would be fine, except the default dealloc implementation for UITableViewController does not clear the dataSource property of the UITableView (which was set by the default implementation of init).
So, there are probably a couple good workarounds, like deferring the request to reloadData yourself, but the simplest one I can think of is putting this in the implementation of your UITableViewController subclass:
- (void)dealloc {
...
self.tableView.delegate = nil;
self.tableView.dataSource = nil;
[super dealloc];
}
Any additional wisdom would be most welcome.
Jesse's answer works perfect. I just made a slight modification for ARC Support
- (void)dealloc
{
self.tableView.delegate = nil;
self.tableView.dataSource = nil;
}
Double-click your executable in the Groups&Files list; click Arguments tab; click "+" in lower pane, enter "NSZombieEnabled", set value to YES, check the box, click red dot to dismiss.
Now run your test case again, and it will tell you which object has been deallocated.
I suspect it's the array backing your tableView in tab2V2.
Make sure your memory handling is correct (is it retained and released correctly?).
You can try this to avoid the problem:
-(void)viewWillAppear:(BOOL)animated
{
if (animated)
{
[self.tableView reloadData];
}
}
When navigating from a tab bar controller, the view will not be animated. So if the view is appearing just for an instant before popping to the root, it won't attempt to reload the table data.
Had a similar problem and Im pretty sure it has something to do with the new SDK to be honest. The following code worked fine before. I have one navigationcontroller and a new one pushed on to that with 3 different views that gets put onto it (Think: changing password where you have 3 different steps: control, change, repeat.) If the user types the wrong password you will first be pushed of the "changing password controller" and then be pushed to the first page (logged out).
This worked before:
-(void)logout {
[self.presentedViewController dismissModalViewControllerAnimated:TRUE];
self.localNavigationController = nil;
[self.navigationController popToRootViewControllerAnimated:TRUE];
}
The way you could solve this is by change ViewWillAppear to ViewDIDAppear. You might have some lagg but atleast it doesnt crash :)
While Jesse's answer provided insight into the semantics around this problem, in my case the underlying cause was different. Just thought I'd mention it in case someone finds himself in the same situation.
I was seeing the error message
* -[UIAnimator removeAnimationsForTarget:]: message sent to deallocated instance ...
where the object in question was a UITableViewCell. On inspection, there were no memory allocation issues in my code.
The problem turned out to be that I was calling one of the popViewController:animated: family of methods from a non-UI thread. This thread had been created to run some network operations and database processing tasks. I simply moved the invocation of the pop method to the UI thread and found that I stopped getting the error.

Resources