title: EXC_BAD_ACCESS second time I start my application and call reloadTable
body: <p>NOTE: THE PROBLEM IS NOT IN THIS CODE, BUT THE ANSWER FOR EXC_BAD_ACCESS is what @strange said.</p>
  
  <p>I am getting this EXC_BAD_ACCESS after viewForHeaderInSection method gets called, guys I have been debugging this for last couple of hours now, so the first time my table gets loaded here is the sequence of the method that gets called.</p>
  
  <p>NOTE: I have two sections each with one row only.</p>
  
  <ol>
  <li>numberOfSectionsInTableView</li>
  <li>viewForHeaderInSection (for section 1)</li>
  <li>heightForHeaderInSection (for section 1)</li>
  <li>numberOfRowsInSection (for section 1)</li>
  <li>heightForRowAtIndexPath (for section 1, row 0)</li>
  <li>viewForHeaderInSection (for section 0)</li>
  <li>heightForHeaderInSection (for section 0)</li>
  <li>numberOfRowsInSection (for section 0)</li>
  <li>heightForRowAtIndexPath (for section 0, row 0)</li>
  <li>cellForRowAtIndexPath (for section 0, row, 0)</li>
  <li>cellForRowAtIndexPath (for section 1, row, 0)</li>
  <li>viewForHeaderInSection (for section 0)</li>
  <li>viewForHeaderInSection (for section 1)</li>
  </ol>
  
  <p>And then my table get displayed properly.</p>
  
  <p>Now I call </p>
  
  <pre><code> [self.tableView reloadTable]
  </code></pre>
  
  <p>All the above 13 methods get called in the same sequence but after the number 13 my code goes to main method on the following line </p>
  
  <pre><code> int retVal = UIApplicationMain(argc, argv, nil, nil); 
  </code></pre>
  
  <p>showing the EXC_BAD_ACCESS.</p>
  
  <p>I enabled NSZombie in the environment variable but no help, i tried allocation and zombie instrumentation, but couldn't figure out any thing. </p>
  
  <p>Any help will be useful.</p>
  
  <p>EDIT:  I have a customView for section header and on I am adding a customView on cell.contentView </p>
  
  <p>EDIT2: Sorry guys for the confusion, the reloadTable gets executed properly this exception is coming from some other place, I am still trying to find out from where.</p>
  
  <p>EDIT3: Hi I have some more information to share, when I fresh install the application on the simulator, meaning deleting the app from the simulator and installing it fresh from xcode everything works fine, now after fresh install I stop through Xcode and run again through Xcode, i get the following error message with NSZombie</p>
  
  <pre><code> [CALayer retainCount]: message sent to deallocated instance 0x19384fd0
  </code></pre>
  
  <p>somewhere after i reloadTable, I am exactly not sure where that error comes.</p>
  
  <p>(gdb) po 0x19384fd0
  2011-05-01 07:08:06.194 Doot[51635:207] <em>*</em> -[CALayer respondsToSelector:]: message sent to deallocated instance 0x19384fd0</p>
  
  <p>Program received signal SIGTRAP, Trace/breakpoint trap.
  0x012f1657 in <strong><em>forwarding</em></strong> ()
  The program being debugged was signaled while in a function called from GDB.
  GDB has restored the context to what it was before the call.
  To change this behavior use "set unwindonsignal off"
  Evaluation of the expression containing the function (_NSPrintForDebugger) will be abandoned.
  (gdb) backtrace</p>
  
  <p>0  0x012f1657 in <strong><em>forwarding</em></strong> ()</p>
  
  <p>1  0x012f1522 in <strong>forwarding_prep_0_</strong> ()</p>
  
  <p>2  0x012bf990 in CFGetRetainCount ()</p>
  
  <p>3  0x000d9dc1 in CA::release_root_if_unused ()</p>
  
  <p>4  0x0015830f in x_hash_table_remove_if ()</p>
  
  <p>5  0x000da246 in CA::Transaction::commit ()</p>
  
  <p>6  0x000da46d in CA::Transaction::observer_callback ()</p>
  
  <p>7  0x0136189b in <strong>CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION</strong> ()</p>
  
  <p>8  0x012f66e7 in __CFRunLoopDoObservers ()</p>
  
  <p>9  0x012bf1d7 in __CFRunLoopRun ()</p>
  
  <p>10 0x012be840 in CFRunLoopRunSpecific ()</p>
  
  <p>11 0x012be761 in CFRunLoopRunInMode ()</p>
  
  <p>12 0x01ec71c4 in GSEventRunModal ()</p>
  
  <p>13 0x01ec7289 in GSEventRun ()</p>
  
  <p>14 0x004a1c93 in UIApplicationMain ()</p>
  
  <p>15 0x000025d4 in main (argc=1, argv=0xbfffef2c) at main.m:13</p>
  
  <p>Sequence of flow after which i get this exception.</p>
  
  <p>I am running async nsurlconnection, once i get back the response in connectionDidFinishLoading, i save that data to the database, by calling a method let us call it saveData in my databasehelper class, in the saveData method I set a boolean variable </p>
  
  <pre><code>   dataSaved = YES 
  </code></pre>
  
  <p>Two of my view controller(having a table in it) are observing this boolean variable, and as soon as the variable set to YES, those two view controller get notified on their </p>
  
  <pre><code> (void)observeValueForKeyPath:(NSString *)keyPath
                    ofObject:(id)object
                      change:(NSDictionary *)change
                     context:(void *)context 
  </code></pre>
  
  <p>I reload the table, once the reload table is done, YES it is done, the control goes back to 
  connectionDidFinishLoading and then it exist properly and then boom I get this exception, i have freaking no idea from which line of my code this exception is coming.</p>
  
  <p>Also what is interesting is, if i don't set that boolean flag dataSaved = YES then the observeValueForKeyPath doesn't get called and my table doesn't reload, in that case my exception doesn't crash. that's why initially i thought it is due to the reload of the table, and actually that can be still true.</p>
  
  <p>I am putting some of my code to explain the flow</p>
  
  <p>MyAppDelegate.m</p>
  
  <pre><code>if ([facebook isSessionValid]) {  
      locationHelper = [LocationHelper sharedInstance];
      tabBarController = [[AppTabBarController createTabBarController:self] retain];
      [self.window addSubview:tabBarController.view];
  }else{
      loginPageController = [[LoginPageController alloc]initWithFacebook:facebook];
      loginNavigationController = [[UINavigationController alloc] initWithRootViewController:loginPageController];
      loginNavigationController.navigationBar.barStyle = UIBarStyleBlack;
      loginPageController.navigationItem.hidesBackButton = YES;
      [self.window addSubview:loginNavigationController.view];
      [loginPageController release];
      //[localNavigationController release];
  }
  </code></pre>
  
  <p>AppTabBarController.m</p>
  
  <pre><code>+ (UITabBarController*) createTabBarController:(id)delegate {
     UINavigationController *localNavigationController;
     NSMutableArray *localControllersArray = [[NSMutableArray alloc] initWithCapacity:2];
  
  
     FirstViewController *firstTabController = [[FirstViewController alloc]init];
     localNavigationController = [[UINavigationController alloc]   
        initWithRootViewController: firstTabController];
  localNavigationController.navigationBar.barStyle = UIBarStyleBlack;
      [localControllersArray addObject:localNavigationController];
  
     // release since we are done with this for now they are not part of the array
     [localNavigationController release];
     [firstTabController release];
  
      FirstViewController *secondTabController = [[FirstViewController alloc]init];
  localNavigationController = [[UINavigationController alloc]           
       initWithRootViewController: secondTabController];
       localNavigationController.navigationBar.barStyle = UIBarStyleBlack;
       [localControllersArray addObject:localNavigationController];
  
  // release since we are done with this for now they are not part of the array
  [localNavigationController release];
  [secondTabController release];
  
  
  UITabBarController* tabBarController = [[[UITabBarController alloc] init ] autorelease];
  
  // load up our tab bar controller with the view controllers
  tabBarController.viewControllers = localControllersArray;
  tabBarController.delegate = delegate;
  // release the array because the tab bar controller now has it
  [localControllersArray release];
  return tabBarController;
  </code></pre>
  
  <p>}</p>
  
  <p>LoginPageController.m</p>
  
  <pre><code> -(id)initWithFacebook:(Facebook*)facebookInstance{
  self.facebook = facebookInstance;
  return self;
     }
  
    - (IBAction)fbButtonClick:(id)sender {
  NSArray *permissions;
  permissions =  [NSArray arrayWithObjects:
                  @"email", nil];
  [facebook authorize:permissions delegate:self];
    }
  
   - (void)fbDidLogin {
  NSLog(@"Inside LoginpageController fbDidLogin");
  //NSLog(@"Access Token is %@", facebook.accessToken );
  //NSLog(@"Expiration Date is %@", facebook.expirationDate );
  // Store the value in the NSUserDefaults
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
      [defaults setObject:facebook.accessToken forKey:ACCESS_TOKEN_KEY];
      [defaults setObject:facebook.expirationDate forKey:EXPIRATION_DATE_KEY];
      [defaults synchronize];
  
  // This is the best place to get user details because here we know that user has already logged in
  [facebook requestWithGraphPath:@"me" andDelegate:self];
  </code></pre>
  
  <p>}</p>
  
  <pre><code>   - (void)request:(FBRequest *)request didLoad:(id)result {
          NSLog(@"Inside LoginPageController didLoad");
           //NSLog(@"request returns user data %@",result);
          MyAppDelegate* myAppDelegate = (MyAppDelegate*)[[UIApplication    sharedApplication]delegate];
          [self.navigationController pushViewController:[AppTabBarController myAppDelegate] animated:YES];
  
      }
  </code></pre>
  
  <p>LocationHelper.m
  //When this get initialize i do </p>
  
  <pre><code> [self.locationManager startUpdatingLocation];
  
   - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
  //if the time interval returned from core location is more than two minutes we ignore it because it might be from an old session
          [self.locationManager stopUpdatingLocation];
          self.currentLocation = newLocation;
          [self updateDataBase];
  
   }
  
   -(void)updateDataBase{
  NSLog(@"Inside updateDataBase");
  BackendHelper *backendHelper = [BackendHelper sharedInstance];
  [backendHelper getData];
  </code></pre>
  
  <p>}</p>
  
  <p>BackendHelper.m</p>
  
  <pre><code> -(void) getData{
  
   NSURL *getURL = [NSURL URLWithString: @"my url"];  
  
  NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
  
  //add our HTTP headers and URL
  [request setValue: @ "plain/text" forHTTPHeaderField : @"Content-Type"];
  [request setHTTPMethod:@"GET"];
  [request setURL : getURL];
  
  
  // Use NSURLConnection to asynchronously download the data. This means the main thread will not
  // be blocked - the application will remain responsive to the user. 
  //
  // IMPORTANT! The main thread of the application should never be blocked!
  // Also, avoid synchronous network access on any thread.
  //
  
   NSURLConnection* urlConnection =
     [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
  </code></pre>
  
  <p>}</p>
  
  <pre><code> - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  // check for HTTP status code for proxy authentication failures
  // anything in the 200 to 299 range is considered successful,
  // also make sure the MIMEType is correct:
  //
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  if ((([httpResponse statusCode]/100) == 2) &amp;&amp; [[response MIMEType] isEqual:@"text/html"]) {
      NSLog(@"Response status code is:%d", [httpResponse statusCode]);
      self.responseData = [[NSMutableData alloc] init];
  } else { 
      NSLog(@"didReceiveResponse error");
  }
  </code></pre>
  
  <p>}</p>
  
  <pre><code> - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
      NSLog(@"didReceiveData");
  [responseData appendData:data];
  }
  
  - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  NSLog(@"didFailWithError");
  </code></pre>
  
  <p>}</p>
  
  <pre><code>- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  NSLog(@"connectionDidFinishLoading");
  [self handleResponseData:responseData];
  [self.responseData release];
  self.responseData = nil;
  }
  
  
  
  - (void) handleResponseData:(NSData*)data {
  NSString * strResult = [[NSString alloc] initWithData: data encoding:NSUTF8StringEncoding];
  [[DatabaseHelper sharedInstance] saveData: strResult];
  [strResult release];
  }
  
  -(void) saveData:(NSString*) strResult{
  // save data to the database
  
  dataSaved = YES;
  </code></pre>
  
  <p>}</p>
  
  <p>FirstViewController.m</p>
  
  <pre><code>- (void)viewDidLoad 
  {   
  [databaseHelper addObserver:self forKeyPath:@"dataSaved" options:NSKeyValueObservingOptionNew context:nil];
  uiTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 372) style:UITableViewStylePlain];
  uiTableView.dataSource = self;
  uiTableView.delegate = self;
  uiTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"doot_background.png"]];
  self.uiTableView.backgroundColor = background;//[UIColor blackColor];
  uiTableView.scrollEnabled = NO;
  [background release];
  [self.view addSubview:uiTableView];
  
  }
  
  - (void)observeValueForKeyPath:(NSString *)keyPath
                    ofObject:(id)object
                      change:(NSDictionary *)change
                     context:(void *)context 
  {
  if([keyPath isEqualToString:@"dataSaved"]){
  
      DatabaseHelper *databaseHelperObject = (DatabaseHelper*)object;
      if(databaseHelperObject.dootUpdated){
              //getData from the database
              [self.uiTableView reloadData];
          }
  }
  }
  </code></pre>