title: iPhoneDev, UITabBarController SelectedIndex Problems
body: <p>I am trying to programmatically switch the tab bar item.  The following code works fine, but I can't get it to work in certain situations:</p>
  
  <pre><code>self.tabBarController.selectedIndex = 0;
  </code></pre>
  
  <p>Here is the problem:</p>
  
  <p>I have a tab bar controller with two UIViewController classes.  In the second tab, I have the code above placed inside an if statement within the viewWillAppear method.  The code above itself works, but it only works if the view has never been loaded.  So, on the first tab I have a button.  When that button is pushed, I programmatically switch to the second tab.  At that point my code works, and I essentially stay on the first tab.  But the switching doesn't work after that first time.  It also doesn't work if I select that second tab before I press that button.  The IF statement that my code is inside fires, but the selected tab doesn't change.</p>
  
  <p>Any help would be appreciated.  Please don't hesitate to ask for clarification if you need it.</p>
  
  <p>Thanks!</p>
  
  <hr>
  
  <p>Let me add more information:</p>
  
  <p>(1) This is only used on rare occassion.  The first screen is a search screen.  After you press search, you are taken to the second tab automatically, unless there are no results, then you are alerted and you stay there.</p>
  
  <p>(2)  The second tab maintains a list of either all items, if no search to narrow down has been performed, or the the list of narrowed down items.  Either way, that list is always available.  So even though I stop them on the search page, if they forget and click the other tab, they will be informed there are no items.  At this point I would like to bring them back to tab one, as a convience only.  </p>
  
  <p>It's not THAT big of a deal, I can live without it, and it's not the horrible programming scheme that some are making it out to be.  I just wanted to add that one user convienence item ...</p>
  
  <hr>
  
  <p>Thanks to tc!  I used the following method in my UITabBarControllerDelegate:</p>
  
  <pre><code>- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
  
  if(self.tabBarController.selectedIndex == 0){
      if([books count] == 0){
  
          [self alertNoResults];
  
          return(FALSE);
      }
  }
  return(TRUE);
  }
  </code></pre>
  
  <p>Worked like a charm!  </p>